Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force a UITableView to reloadData while keeping a UISearchBar active?

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?

like image 502
MahatmaManic Avatar asked Feb 24 '23 22:02

MahatmaManic


2 Answers

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 !

like image 90
Christophe Fondacci Avatar answered Apr 09 '23 14:04

Christophe Fondacci


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.

like image 30
Mark Adams Avatar answered Apr 09 '23 14:04

Mark Adams