标签:uisearchdisplaycontr 搜索通讯录 tableview加searchbar
使用的是storyBoard
1拖一个UISearchDisplayController到tableView的headerView上,并声明成全局变量
@property (strong, nonatomic) IBOutlet UISearchDisplayController *searchDispalyController;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (nonatomic, strong) NSArray * resultModelArr;
2实现代理方法
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
NSPredicate* cate=[NSPredicate predicateWithFormat:@"(SELF.name contains [c] %@) OR ( SELF.phone contains [c] %@)",
self.searchBar.text,
self.searchBar.text
];
self.resultModelArr=[self.modelArray filteredArrayUsingPredicate:cate];
//modelArray 封装的person对象,有name和phone两种属性
}
#pragma mark - UISearchDisplayController delegate methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
[self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:[[self.searchDisplayController.searchBar scopeButtonTitles] 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.tableView dequeueReusableCellWithIdentifier:@"PhoneContactCell" forIndexPath:indexPath];//要用self.tableView 否则会崩溃
PhoneContactModel * model;
if (tableView == self.searchDispalyController.searchResultsTableView) {
model= _resultModelArr[indexPath.row];
}else{
model= _modelArray[indexPath.row];
}
[cell setModel:model];
return cell;
}
标签:uisearchdisplaycontr 搜索通讯录 tableview加searchbar
原文地址:http://blog.csdn.net/mingios/article/details/40861177