- (void)createSearchBar
{
_searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, kLineHeight)];
[_searchBar setShowsCancelButton:YES animated:YES];
[_searchBar setBarStyle:UIBarStyleBlack];
_searchBar.delegate = self;
_mySearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
_mySearchDisplayController.searchResultsTableView.rowHeight = kTableViewRowHeight;
_mySearchDisplayController.searchResultsTableView.backgroundColor = [UIColor colorWithWhite:0.200 alpha:1.000];
_mySearchDisplayController.delegate = self;
_mySearchDisplayController.searchResultsDelegate = self;
_mySearchDisplayController.searchResultsDataSource = self;
self.tableView.tableHeaderView = _searchBar;
}
#pragma mark - search display controller delegate
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:[[_mySearchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[_mySearchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
#pragma mark - filter
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:@"Title CONTAINS %@",
searchText];
_searchResult = [self.passArrayDataSource filteredArrayUsingPredicate:resultPredicate];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (tableView == _mySearchDisplayController.searchResultsTableView) {
return [_searchResult count];
}
else
return [_sortedArrayDataSource count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// fixed: unable to dequeue a cell with identifier
//UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// Configure the cell...
NSDictionary *dic = [[NSDictionary alloc] init];
if (tableView == _mySearchDisplayController.searchResultsTableView)
dic = _searchResult[indexPath.row];
else
dic = _sortedArrayDataSource[indexPath.row];
...
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == _mySearchDisplayController.searchResultsTableView) {
...
}
}