I've got a UITableView in which I set its header to be a search bar.
tableView.tableHeaderView = searchController.searchBar
Everything works according to plan until you click it and it seemingly detaches from the tableView and jumps to the top of the screen. The tableView rows stay in place. Any reason it would do that in iOS 11 and not iOS 10?
It is encouraged to apply the new way to show search bar/search controller on iOS 11. Here is what I have done:
if #available(iOS 11.0, *) {
navigationItem.searchController = searchController
} else {
tableView.tableHeaderView = searchController.searchBar
}
I had the exact same issue - weird jumping behaviour of the UISearchBar on iOS11, where on iOS10 everything is fine.
Regarding the advice by Simon Wang above - the problem I had there is that I am not defining my UISearchBar
inside a UIViewController
, I am instead inside another UITableViewCell
- so therefore I don't have access to the navigationItem
and can't present my search bar that way.
Anyway, after much trial and error, the only way I could get things working was to scrape the UISearchController
and related delegates altogether.
Instead I define a UISearchBar
inside Interface Builder, and define its layout constraints as appropriate. I then make its parent class conform to UISearchBarDelegate
and do searchBar.delegate = self
I then add a bunch of delegate methods to catch content changes to the search bar, and update my table results accordingly:
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
filterContentForSearchText(self.searchBar.text!)
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
filterContentForSearchText(self.searchBar.text!)
self.searchBar.resignFirstResponder()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filterContentForSearchText(self.searchBar.text!)
}
And life is good again. Hope this helps!
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