Search code examples
iosobjective-cuitableviewuisearchbaruisearchcontroller

Implement UISearchController in UITableView Objective-C


I'm following this tutorial to implement UISearchController in my project : http://useyourloaf.com/blog/updating-to-the-ios-8-search-controller.html

I succeed to find with deprecated method (searchDisplayController) but I would like to implement UISearchController.

Well, in my viewDidLoad I've implemented :

//UISearchController
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.searchBar.delegate = self;
self.tableView.tableHeaderView = self.searchController.searchBar;
self.searchController.searchBar.scopeButtonTitles = @[];
self.definesPresentationContext = YES;
[self.searchController.searchBar sizeToFit];

In my numberOfRowsInSection, I've let my old code for searchDisplayController :

if (table == self.searchDisplayController.searchResultsTableView)
{
    return [self.searchResults count];
}
else
{
    return [self.allUsers count];
}

In my cellForRowAtIndexPath :

NSArray *sourceData = (tableView == self.searchDisplayController.searchResultsTableView ? self.searchResults : self.allUsers);
PFUser *selected = [sourceData objectAtIndex:indexPath.row];
NSString *name = [[sourceData objectAtIndex:indexPath.row] valueForKey:@"surname"];
cell.textLabel.text = name;

and added these methods :

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSString *searchString = searchController.searchBar.text;
    [self searchForText:searchString];
    [self.tableView reloadData];
    NSLog(@"updateSearchResultsForSearchController");
}

- (void)searchForText:(NSString*)searchText
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"surname contains[c] %@", searchText];
    self.searchResults = [self.allUsers filteredArrayUsingPredicate:predicate];

}

- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
{
    [self updateSearchResultsForSearchController:self.searchController];
}

Well, when I click on the search bar and tap some words, the log updateSearchResultsForSearchController appears. But the person I search doesn't appear. I don't know what I've to implement for that works ? Maybe my searchForText:searchString method isn't right ?

Or maybe I've to add something in my cellForRowAtIndexPath and numberOfRowsInSection ?


Solution

  • First, you should check self.searchResults.count. If self.searchResults.count > 0, method searchForText:searchString is right. So you check problem in tableView.