iOS8之前我们使用UISearchDisplayController做TableView的本地搜索
iOS8提供实现搜索功能的SDK:UISearchController(iOS8.0之后)、UISearchDisplayController(iOS8.0之前,iOS8.0之后不建议再使用)。
遵守UISearchResultsUpdating协议
1 @interface ZWRecommendationFocusViewController()<UISearchResultsUpdating> 2 @property (strong, nonatomic) NSArray *list; 3 @property (strong, nonatomic) NSMutableArray *searchList; 4 @property (strong, nonatomic)UISearchController *searchController; 5 @end
1 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 2 { 3 return (!self.searchController.active)?1:1; 4 } 5 6 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 7 { 8 return (!self.searchController.active)?self.list.count:self.searchList.count; 9 } 10 11 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 12 { 13 ZWFocusList *list=(!self.searchController.active)?self.list[indexPath.row]:self.searchList[indexPath.row]; 14 static NSString *identifier = @"cell"; 15 ZWFocusListTableViewCell *cell = [ZWFocusListTableViewCell cellWithTableView:tableView identifier:identifier]; 16 cell.list = list; 17 return cell; 18 }
1 /** 2 * UISearchController作为UITableView的tableHeaderView 3 */ 4 -(void)addSearchBar 5 { 6 //创建UISearchController对象 7 UISearchController *searchController = [[UISearchController alloc]initWithSearchResultsController:nil]; 8 //是否添加半透明覆盖层。为YES,搜索时,背景会变暗(背景变模糊)。默认为YES 9 searchController.dimsBackgroundDuringPresentation = NO; 10 //是否隐藏导航栏。为YES,搜索时,UINavigationBar会隐藏。默认为YES 11 searchController.hidesNavigationBarDuringPresentation = YES; 12 //NO表示UISearchController在present时,可以覆盖当前controller。默认为NO 13 searchController.definesPresentationContext = NO; 14 //搜索栏表头视图 15 self.tableView.tableHeaderView = searchController.searchBar; 16 17 [searchController.searchBar sizeToFit]; 18 searchController.searchResultsUpdater = self; 19 20 searchController.searchBar.placeholder=@"请输入名称或者数字"; 21 searchController.searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone; 22 // searchController.searchBar.showsCancelButton=YES;//显示取消按钮 23 //自适应 24 [searchController.searchBar sizeToFit]; 25 // searchController.searchBar.frame = CGRectMake(0, 0, 0, 44); 26 // searchController.searchBar.prompt=@"请输入关键字"; 27 self.searchController = searchController; 28 }
1 - (void)updateSearchResultsForSearchController:(UISearchController *)searchController{ 2 NSString *searchString = self.searchController.searchBar.text; 3 //NSPredicate 谓词 4 NSPredicate *preicate = [NSPredicate predicateWithFormat:@"theme_name LIKE[c] %@", searchString]; 5 if (self.searchList!= nil) { 6 [self.searchList removeAllObjects]; 7 } 8 //过滤数据 9 self.searchList= [NSMutableArray arrayWithArray:[self.list filteredArrayUsingPredicate:preicate]]; 10 //刷新表格 11 [self.tableView reloadData]; 12 }