项目中需要一个简单的搜索功能,基于此,首先想到的就是SearchBar了,以前没怎么接触过,以前一般是自己通过textfield来实现的,这次想通过这个来试试系统提供的.
@property (nonatomic ,strong)UISearchController *searchVC;
@property (nonatomic ,strong)NSMutableArray *exampleArr;
@property (nonatomic ,strong)NSMutableArray *searchArr;
先全局UISearchController和建数组.
再初始化
_searchVC = [[UISearchController alloc]initWithSearchResultsController:nil];
_searchVC.searchResultsUpdater = self;//代理
_searchVC.delegate = self;//代理
_searchVC.dimsBackgroundDuringPresentation = NO;//蒙版
_searchVC.hidesNavigationBarDuringPresentation = NO;//开启后自动至导航栏
self.definesPresentationContext = YES;//是否push界面后,隐藏搜索,返回后继续显示
_tableView.tableHeaderView = self.searchVC.searchBar;//添加上
#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
NSString *searchString = [self.searchVC.searchBar text];
NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
if (self.searchArr!= nil) {
[self.searchArr removeAllObjects];
}
//过滤数据
self.searchArr= [NSMutableArray arrayWithArray:[_exampleArr filteredArrayUsingPredicate:preicate]];
//刷新表格
[_tableView reloadData];
}