After updating to iOS11 my searchBar behaves strange

653 Views Asked by At

After updating to iOS11 my searchBar behaves very strange. When activated, it jumps to the top of screen. It works as it should, as before but of course I want it to stay in place. I have tried a lot of solutions from googling this behavior but nothing helps. Do anyone have the same problem? And what did you do to solve this?

searchBar in place

searchBar jumped to top

var searchController: UISearchController!


        override func viewDidLoad() {
            super.viewDidLoad()
            // Setup the Search Controller
            searchController = UISearchController(searchResultsController: nil)
            searchController.searchResultsUpdater = self
            searchController.dimsBackgroundDuringPresentation = false
            searchController.hidesNavigationBarDuringPresentation = false
            searchController.searchBar.preservesSuperviewLayoutMargins = true
            searchController.obscuresBackgroundDuringPresentation = false
            searchController.searchBar.sizeToFit()
            walkaboutTableView.tableHeaderView = searchController.searchBar
            searchController.searchBar.barTintColor = matildaLightBlue
            searchController.searchBar.clipsToBounds = true
            searchController.searchBar.layer.borderWidth = 2
            searchController.searchBar.layer.borderColor = UIColor.black.cgColor
    }
2

There are 2 best solutions below

2
On

Adding search controller instance into navigation item instead of table header view helps me to solve similar issue in my project.

if #available(iOS 11, *) {
   navigationItem.searchController = searchController
} else {
   tableView.tableHeaderView = searchController.searchBar
}

navigationItem.searchController

navigationItem.hidesSearchBarWhenScrolling

0
On

Ruslan Kolosovskyi's answer is really good. In addition if you want the search bar to be more accessible:

    if #available(iOS 11, *) {
       navigationItem.searchController = searchController

       navigationItem.hidesSearchBarWhenScrolling = false
    } else {
       tableView.tableHeaderView = searchController.searchBar
    }