Filtering a UITableView, and keyboard wonkiness
Hey, another bug that took half a day to fix. That always deserves a blog entry.
So I have a UITableView, and on it I have a tableHeaderView containing a UISearchBar. The UISearchBar filters the contents of the UITableView, and thus at every key press I have to reloadData (or more specifically, I -[UITableView reloadSections:withRowAnimation:]). For some reason, this calls setUserInteractionEnabled:NO on the UITableView, which in turn makes the UISearchBar’s UIFieldEditor resignFirstResponder, which makes the keyboard collapse. After the reload, user interaction is restored, UISearchBar gets focus, and the keyboard comes up.
This is rather embarrassing: I even subclassed UITableView, disabling setUserInteractionEnabled, before I realized that right there, before my eyes, is a UISearchBar delegate method called -[UISearchBarDelegate searchBarShouldEndEditing:]. Just add a bool ivar to the view controller saying whether the search bar may be resign key, set it to false before refreshing, refresh, and set it to true, and in the above delegate, return the ivar bool. Done, no more disappearing and reappearing keyboards.
Oh, and the code:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
_searchBarMayResign = NO;
[self.tableView reloadData]; // or equivalent
_searchBarMayResign = YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar;
{
return _searchBarMayResign;
}