iOS開發---簡單地搜尋

來源:互聯網
上載者:User

標籤:

iOS8之後我們就可以直接運用UISearchController的代理方法進行開發,不用再UIsearch和其他的一下東西了,我就直接給大家上代碼吧

UISearchBarDelegate,UISearchResultsUpdating這兩個代理方法

viewdidload:

self.dataList=[NSMutableArray arrayWithCapacity:100];        for (NSInteger i=0; i<100; i++) {        [self.dataList addObject:[NSString stringWithFormat:@"%ld-FlyElephant",(long)i]];    }    ALog(@"-====%lu",(unsigned long)self.dataList.count);  tableview =[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];    tableview.delegate =self;    tableview.dataSource =self;    [self.view addSubview:tableview];  _search =[[UISearchController alloc]initWithSearchResultsController:nil];    _search.searchResultsUpdater =self;    _search.dimsBackgroundDuringPresentation = NO;    _search.hidesNavigationBarDuringPresentation = NO;    _search.searchBar.frame = CGRectMake(_search.searchBar.frame.origin.x, _search.searchBar.frame.origin.y, _search.searchBar.frame.size.width, 44);
//當做表的頭視圖 tableview.tableHeaderView = _search.searchBar;

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//一定要判斷狀態 if (_search.active) { return [self.searchList count]; } else{ return [self.dataList count]; }}-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *flag=@"cellFlag"; UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:flag]; if (cell==nil) { cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:flag]; } if (_search.active) { [cell.textLabel setText:self.searchList[indexPath.row]]; } else{ [cell.textLabel setText:self.dataList[indexPath.row]]; } return cell; }-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{ NSString *searchString =[_search.searchBar text];
//篩選語句 NSPredicate *predicate =[ NSPredicate predicateWithFormat:@"SELF CONTAINS[c]%@",searchString]; if (self.searchList !=nil) { [self .searchList removeAllObjects]; } self.searchList = [NSMutableArray arrayWithArray:[self.dataList filteredArrayUsingPredicate:predicate]]; ALog(@"-==%ld",self.searchList.count); [tableview reloadData]; }

 

iOS開發---簡單地搜尋

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.