Search code examples
swiftxcodeuser-interfaceuibuttonuisearchcontroller

UISearchController changing view after being pressed


I am currently creating my first Swift application, and I have a search bar implemented like

private func addSearchBar() {
    let searchController = UISearchController(searchResultsController: nil)
    
    navigationItem.titleView = searchController.searchBar
    definesPresentationContext = true
}

Obviously there is no logic other than displaying the search bar, but I was curious if there was a way to make it so when a user pressed the search bar, it would just switch to another view. I have been able to successfully implement changing views with UIButtons, but I am unfamilair with UISearchController, and I would like it to act just like a UIButton if possible. Thanks!


Solution

  • First set the search bar's delegate to your view controller. In your case

    searchController.searchBar.delegate = self
    

    then conform to the UISearchBarDelegate and add the following method in order to detect when you tap the search bar.

    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
        // your code to show another view or view controller
    }