4

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?

MahatmaManic
  • 943
  • 1
  • 8
  • 16

3 Answers3

5

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 !

3

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.

Mark Adams
  • 30,776
  • 11
  • 77
  • 77
  • This isn't quite what I wanted, but for the amount of hassle it saved to implement it's probably close enough. Thanks. – MahatmaManic Mar 04 '11 at 08:00
0

I had similar problem. It turned out that it had to do with animations I used when table was reloading data. When I removed reloadSections:withRowAnimation, and simply called:

[self.tableView reloadData];

instead of calling fancier methods with animations for refreshing the table data, the search bar did not resign first responder on any key entered anymore.

Hope this helps...

Despotovic
  • 1,807
  • 2
  • 20
  • 24