Search code examples
iosswiftuisearchcontrollercancel-button

UISearchController Cancel Button Not Clickable


There are a lot of questions/answers to this but unfortunately none of them work.

I have a subclass of UICollectionViewController, which I want its collectionView items to be searchable. I therefore use a UISearchController but handle the filtered collectionView items in self, so set the searchResultsController to nil.

class CollectionViewController: UICollectionViewController {

    var searchController: UISearchController!

    override func viewDidLoad() {

        super.viewDidLoad()

        self.becomeFirstResponder()

        searchController = UISearchController(searchResultsController: nil)
        searchController.delegate = self
        searchController.searchBar.delegate = self
        searchController.searchBar.isUserInteractionEnabled = true

        navigationItem.searchController = searchController

    }

}      

I implement the required delegate methods as follows:

extension CollectionViewController:: UISearchControllerDelegate {
}

extension CollectionViewController:: UISearchBarDelegate {

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        collectionView?.reloadData()
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        print("searchBarCancelButtonClicked")
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        print("searchBarSearchButtonClicked")
    }

    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        print("searchBarTextDidEndEditing")
        collectionView?.reloadData()
    }

}

I can enter text into the search bar, filter my collection view and reload it successfully as I enter text. Furthermore, I can click "Search" on the keyboard, which calls the searchBarSearchButtonClicked method.

enter image description here

However, although the Cancel button is visible (see above), it does not seem to be clickable. Thus, the searchBarCancelButtonClicked method does not get called.

What am I doing wrong here, please?


Solution

  • Make sure to call definesPresentationContext = true after you declare your delegate

    class CollectionViewController: UICollectionViewController {
    
        var searchController: UISearchController!
    
        override func viewDidLoad() {
    
            super.viewDidLoad()
    
            self.becomeFirstResponder()
    
            searchController = UISearchController(searchResultsController: nil)
            searchController.delegate = self
            searchController.searchBar.delegate = self
    
            self.definesPresentationContext = true .  // ADD 
    
            searchController.searchBar.isUserInteractionEnabled = true
    
            navigationItem.searchController = searchController
    
        }
    
    }