首页 > 代码库 > tableView加searchBar,以搜索通讯录为列
tableView加searchBar,以搜索通讯录为列
使用的是storyBoard
1拖一个UISearchDisplayController到tableView的headerView上,并声明成全局变量
@property (strong,nonatomic) IBOutletUISearchDisplayController *searchDispalyController;
@property (weak, nonatomic) IBOutletUISearchBar *searchBar;
@property (nonatomic,strong) NSArray * resultModelArr;
2实现代理方法
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
NSPredicate* cate=[NSPredicatepredicateWithFormat:@"(SELF.name contains [c] %@) OR ( SELF.phone contains [c] %@)",
self.searchBar.text,
self.searchBar.text
];
self.resultModelArr=[self.modelArrayfilteredArrayUsingPredicate:cate];
//modelArray 封装的person对象,有name和phone两种属性
}
#pragma mark - UISearchDisplayController delegate methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[selffilterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBarscopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
[selffilterContentForSearchText:[self.searchDisplayController.searchBartext] scope:[[self.searchDisplayController.searchBarscopeButtonTitles]objectAtIndex:searchOption]];
return YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (tableView == self.searchDispalyController.searchResultsTableView) {
return_resultModelArr.count;
}else{
return _modelArray.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
PhoneContactCell *cell = [self.tableViewdequeueReusableCellWithIdentifier:@"PhoneContactCell"forIndexPath:indexPath];//要用self.tableView 否则会崩溃
PhoneContactModel * model;
if (tableView == self.searchDispalyController.searchResultsTableView) {
model=_resultModelArr[indexPath.row];
}else{
model=_modelArray[indexPath.row];
}
[cellsetModel:model];
return cell;
}
tableView加searchBar,以搜索通讯录为列