項(xiàng)目中需要一個(gè)簡(jiǎn)單的搜索功能,基于此,首先想到的就是SearchBar了,以前沒怎么接觸過,以前一般是自己通過textfield來實(shí)現(xiàn)的,這次想通過這個(gè)來試試系統(tǒng)提供的.
@property (nonatomic ,strong)UISearchController *searchVC;
@property (nonatomic ,strong)NSMutableArray *exampleArr;
@property (nonatomic ,strong)NSMutableArray *searchArr;
先全局UISearchController和建數(shù)組.
再初始化
_searchVC = [[UISearchController alloc]initWithSearchResultsController:nil];
_searchVC.searchResultsUpdater = self;//代理
_searchVC.delegate = self;//代理
_searchVC.dimsBackgroundDuringPresentation = NO;//蒙版
_searchVC.hidesNavigationBarDuringPresentation = NO;//開啟后自動(dòng)至導(dǎo)航欄
self.definesPresentationContext = YES;//是否push界面后,隱藏搜索,返回后繼續(xù)顯示
_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];
}
//過濾數(shù)據(jù)
self.searchArr= [NSMutableArray arrayWithArray:[_exampleArr filteredArrayUsingPredicate:preicate]];
//刷新表格
[_tableView reloadData];
}