Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 11 hides scope bar after first presentation of the search controller

I am trying to use UISearchController to display a search bar along with scope bar in iOS 11.

Here is the code that I am using to setup the search controller

let searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false

searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.showsScopeBar = true
searchController.searchBar.scopeButtonTitles = ["1", "2", "3", "4"]
searchController.searchBar.delegate = self
definesPresentationContext = true

I want a search bar with a scope bar that is always visible. The above code works fine when the view controller loads and it displays the search bar along with the scope bar.

But, once the search controller becomes active and is then dismissed, iOS hides the scope bar on dismiss of the search controller and it only displays the search bar.

I tried to solve this issue by adding the following code in didDismissSearchController, but the scope bar and the search bar comes on top of each other instead of the scope bar coming below the search bar (like the image below). Adding this code to searchBarTextDidBeginEditing(_ searchBar: UISearchBar) or searchBarTextDidEndEditing(_ searchBar: UISearchBar) has no effect.

searchController.searchBar.showsScopeBar = true
searchController.searchBar.sizeToFit()

enter image description here

like image 698
Praveen Gowda I V Avatar asked Nov 07 '22 14:11

Praveen Gowda I V


1 Answers

  1. Try adding this this to your search controller setup:

    searchController.sizeToFit()
    
  2. Then add this:

    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
        self.searchBar.sizeToFit()
        return true
    }
    
    func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
        self.searchBar.sizeToFit()
        return true
    }
    

Don't put searchController.searchBar.showsScopeBar = true in the search bar functions. That creates a problem for some reason.

like image 98
Ang Wei Zou Avatar answered Nov 15 '22 11:11

Ang Wei Zou