1.添加searchDispaly控件,添加searchDisplay的属性变量
2.添加属性变量 NSArray *searchResult 作为搜索结果所存储的容器
3.实现UISearchBarDelegate, 和UISearchDispalyDelegate协议
4.关键方法
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
NSPredicate *searchContent=[NSPredicate predicateWithFormat:@"SELF contains[c]%@",searchString];
self.searchResult=[self.lists filteredArrayUsingPredicate:searchContent];
[self.tableView reloadData];
return YES;
}
5.判断显示的numberOfRowsInSection
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (tableView==self.searchDisplay.searchResultsTableView) {
return self.searchResult.count;
}else{
return self.lists.count;
}
}
6.判断显示的cellForRowAtIndexPath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellID=@"ListCell";
// 1.从重用对象池中找不用的cell对象
UITableViewCell *cell=[self.tableView dequeueReusableCellWithIdentifier:cellID];
// 2.如果没有就自己创建
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
// 3. 设置cell的属性
List *list;
if (tableView==self.searchDisplay.searchResultsTableView){
list=self.searchResult[indexPath.row];
}else{
list=self.lists [indexPath.row];
}
cell.textLabel.text=list.name;
return cell;
}
7.疑问
ios 8.0 弃用了UISearchDispalyController推荐使用UISearchController,如何使用UISeachController
http://www.tuicool.com/articles/6viqEn
1.delegate 替换为 UISearchResultsUpdating
2.初始化searchBar
_searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
_searchController.searchResultsUpdater = self;
_searchController.dimsBackgroundDuringPresentation = YES;
_searchController.hidesNavigationBarDuringPresentation = 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.tableView.tableHeaderView = self.searchController.searchBar;
3. 搜索方法
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
NSPredicate *searchPredicate=[NSPredicate predicateWithFormat:@"SELF.name CONTAINS[c] %@",self.searchController.searchBar.text];
self.searchResult=[self.lists filteredArrayUsingPredicate:searchPredicate];
[self.tableView reloadData];
}
未解决 空白搜索不显示全部数组