Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide index bar when searching UITableView

I have implemented a search bar and index capability for my table view. Working well. However, I noticed that when I click in the search bar, the index is still available and clicking on it causes unpredictable results. Rather than debug that, I thought it would be simpler to hide the index :)

I found references elsewhere to calling sectionIndexTitlesForSectionView and returning nil. So, when I click in the search box, in searchBarTextDidBeginEditing I have made an explicit call to [self sectionIndexTitlesForSectionView:[self tableView]].

The result is that sectionIndexTitlesForSectionView does get invoked and return nil, but the index is still present.

Any ideas/suggestions would be greatly appreciated! Tony.

like image 693
Tony Avatar asked Jul 15 '12 18:07

Tony


1 Answers

You have to return nil in - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView if you the search is active, as you note in your post. Then, override two methods from the UISearchDisplayDelegate to refresh the indices.

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller {
    [self.tableView reloadSectionIndexTitles];
}

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller {
    [self.tableView reloadSectionIndexTitles];
}

For the sectionIndexTitlesForTableView method, I prefer to use:

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (self.searchDisplayController.active) {
        return nil;
    } else {
        //Add @"{search}", to beginning to add search icon to top of index
        return @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z", @"#"];
    }
}

NOTE: I found that you must use self.searchDisplayController.activein the if condition. It doesn't work if you use tableView != self.tableView.

like image 102
Mike1in3 Avatar answered Oct 05 '22 23:10

Mike1in3