Search code examples
swiftuisearchcontroller

UISearchController setActive does nothing


I'm trying to present a search controller in response to a button, by setting its isActive property, but it doesn't appear.

lazy var searchController: UISeachController = {
    let searchController = UISearchController(searchResultsController: nil)
    searchController.delegate = self
    return searchController
}()

override func viewDidLoad() {
    super.viewDidLoad()
    definesPresentationContext = true
}

// Called when a button on the navbar is tapped
@obcj private func searchTapped() {
    // The doc says you can force the search controller to appear by setting isActive,
    // but nothing happens
    searchController.isActive = true

    // Calling present does show it, but the search bar appears behind the navbar. 
    // And the delegate methods are still not called
    //present(searchController, animated: true)
}

func willPresentSearchController(_ searchController: UISearchController) {
    // Not called, even when calling 'present'
}

Solution

  • It seems isActive only works if the search bar is in the view hierarchy.

    // This will place the search bar in the title view, allowing you to
    // have other buttons on the right of the search bar.
    navigationItem.titleView = searchController.searchBar
    

    Or

    // This takes up a whole other row under title row.
    navigationItem.searchController = searchController
    

    But if you go this route, you don't need to set isActive yourself - the search controller automatically comes up when the user interacts with the search bar. I still don't understand how isActive is supposed to be used, but it does answer the original question.