iOS 11 search bar jumping to top of screen

前端 未结 5 1986
青春惊慌失措
青春惊慌失措 2020-12-09 19:07

I\'ve got a UITableView in which I set its header to be a search bar.

tableView.tableHeaderView = searchController.searchBar

Everything wor

5条回答
  •  佛祖请我去吃肉
    2020-12-09 19:20

    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!

提交回复
热议问题