开发中经常需要在UITableView添加搜索功能,于是可以利用UISearchDisplayController类,UISearchDisplayController可以和其他需要实现搜索功能的controller类关联起来,它封装了丰富的功能,使用起来也比较简单,特别是要实现全屏搜索功能时,半透明遮盖的效果都已经封装好了。
UISearchDisplayController关键部分代码
在.h文件中的相关代码
@interface TestViewController : UITableViewController{
NSArray *data;
NSArray *filterData;
UISearchDisplayController *searchDisplayController;
}
在.m文件的相关代码
- (void)viewDidLoad
{
[super viewDidLoad];
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width , 50)];
searchBar.placeholder = @"搜索";
self.tableView.tableHeaderView = searchBar;
searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
searchDisplayController.searchResultsDataSource = self;
searchDisplayController.searchResultsDelegate = self;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tableView) {
return data.count;
}else{
//搜索关键词
NSString *key = searchDisplayController.searchBar.text;
searchResult = [self searchByKey:key];
return searchResult.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = @"cell_1";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
}
if (tableView == self.tableView) {
cell.textLabel.text = data[indexPath.row];
}else{
cell.textLabel.text = searchResult[indexPath.row];
}
return cell;
}