Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 11 search bar jumping to top of screen

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?

like image 934
Tyler Rolfe Avatar asked Aug 21 '17 13:08

Tyler Rolfe


2 Answers

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
    }
like image 171
Simon Wang Avatar answered Sep 20 '22 09:09

Simon Wang


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!

like image 28
Ali Parr Avatar answered Sep 22 '22 09:09

Ali Parr