I've got a UITableView that has 20 sections. At the top I have a UISearchBar, and I want to filter the sections live as the user types.
Unfortunately, if the UISearchBar is active and if I return NO from searchBarShouldEndEditing: then my [tableView reloadData] call is ignored. If I return YES from searchBarShouldEndEditing: then the reloadData call works fine but I lose firstResponder after each character typed.
How can I force the UITableView to do live updates and filtering without having to resignFirstResponder on the UISearchBar between each character typed?
I faced the same problem and ended up with a quite elegant solution :
You place your search bar in a specific section of your table (let's say index 0). You place your table data in another section (let's say index 1).
When the text of your search bar changes, you can update your model and then simply call :
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:1];
[self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
This way, your keyboard will still be active, your search bar will still be the first responder, and you will benefit from nice built-in table animations !
You could save yourself a lot of work by using the UISearchDisplayController
and just feeding it the same datasource. It manages the search bar and its own table view for displaying filtered results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With