开发中为ViewController头部添加搜索框的时候,用到了UISearchController,笔者使用时,遇到了一些坑,在此记下来,共勉
1.该ViewController要继承自UITableViewController
2.cell要根据searchController.active的值判断来加载相应数据
3.核心代码如下
UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
searchController.searchResultsUpdater = self;
// searchController.dimsBackgroundDuringPresentation = YES;//搜索时tableView添加蒙版
// searchController.hidesNavigationBarDuringPresentation = NO;//搜索时是否需要隐藏导航栏 默认为YES
searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x,self.searchController.searchBar.frame.origin.y,self.searchController.searchBar.frame.size.width,44.0);
self.searchController = searchController;
self.tableView.tableHeaderView = self.searchController.searchBar;
self.definesPresentationContext=YES;
4.实现代理方法<UISearchResultsUpdating>设置数据来源
#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
NSString *searchString = [self.searchController.searchBar text];
NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
if(self.searchList != nil) {
[self.searchList removeAllObjects];
}
//过滤数据
self.searchList = [NSMutableArray arrayWithArray:[self.dataArray filteredArrayUsingPredicate:preicate]];
//刷新表格
[self.tableView reloadData];
}