標籤:
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開發---簡單地搜尋