How to make UITableView reload data while saving UISearchBar?

I have a UITableView in which there are 20 sections. At the top, I have a UISearchBar, and I want to filter sections in real time, as user types.

Unfortunately, if the UISearchBar is active and if I return NO from searchBarShouldEndEditing: then my call to [tableView reloadData] is ignored. If I return YES from searchBarShouldEndEditing: then the call to reloadData will work fine, but I will lose the firstResponder after each character.

How to get UITableView to do live updates and filtering without having to resignFirstResponder on a UISearchBar between each character entered?

+4
source share
3 answers

You could save a lot of work by using the UISearchDisplayController and simply serving the same data source to it. It controls the search bar and its own tabular view to display the filtered results.

+3
source

I ran into the same problem and turned out to be a pretty elegant solution:

You place your search bar in a specific section of your table (say, index 0). You place the table data in another section (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]; 

That way, your keyboard will still be active, your search bar will still be the first responder, and you will get a nice built-in table animation!

+5
source

I had a similar problem. It turned out that this was due to the animations that I used when the table reloaded the data. When I removed reloadSections:withRowAnimation and just called:

 [self.tableView reloadData]; 

instead of calling fancier methods with animation to update the table data, the search bar did not cancel the first responder to any key entered.

Hope this helps ...

0
source

Source: https://habr.com/ru/post/1342205/


All Articles