前提: UISearchDisplayController 在ios8已经废弃了。
前提1:In Storyboard, drag and add the “Search Bar and Search Display Controller” , 直接拖出来不用实现任何新的代码,你就已经有个 search bar了。 不需要手动连接 data source and delegate with the view controller,它会自动连接。
前提2:设置cell 的高度:统一自定义cell 和 The table view in the search display controller 。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{return71;}
实施:
Implementing Search Filter
1:创建2个数组(recipes用来保存所有的菜单数据,searchResults用来保存搜索的结果)
// 它通过搜索所有的食谱,并返回搜索结果.
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
self.searchResults = [self.tableData filteredArrayUsingPredicate:resultPredicate];
}
Implementing Search Display Controller Delegate
//UISearchDisplayDelegate 定义当搜索字符串改变时,shouldReloadTableForSearchString自动被调用
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
Displaying Search Results
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [self.searchResults count]; //返回 搜索结果的数量
} else {
return [self.tableData count];
}
}
---
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Simple Table Cell";
NewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell=[[NewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// 这里的Recipe类只是定义(name,image,prepTime,ingredients)
Recipe *recipe = nil;
if (tableView == self.searchDisplayController.searchResultsTableView) {
recipe = self.searchResults[indexPath.row];
} else {
recipe = self.tableData[indexPath.row];
}
cell.nameLabel.text = recipe.name;
cell.imageView.image = [UIImage imageNamed:recipe.image];
cell.timeLabel.text = recipe.prepTime;
return cell;
}
----------------------------------------------------------------------------------Cool,it works.
Handling Selection in Search Results
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"Show Detail"]) {
NSIndexPath *indexPath = nil;
Recipe *recipe = nil;
if (self.searchDisplayController.active) {
indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
recipe = self.searchResults[indexPath.row];
} else {
indexPath = [self.tableView indexPathForSelectedRow];
recipe = self.tableData[indexPath.row];
}
RecipeDetailViewController *rdvc = segue.destinationViewController;
rdvc.recipe = recipe;
}
}
a search bar in iOS app,完成。