Search code examples
iosswiftdelegatesuisearchcontroller

UISearchcontroller searchbar delegate not working


class PlaceSelectorViewController: UIViewController, GMSAutocompleteResultsViewControllerDelegate, UISearchBarDelegate {

I have included searchbar delegate

searchController?.searchBar.delegate = self

and I have set the delegate.

But method

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    stopHighlight()
}

doesn't happen.

Delegate has set properly and stopHighlight() is a real function


Solution

  • Make delegate of searchbar in viewdidload method.

     override func viewDidLoad() {
                super.viewDidLoad()
                searchBarCustom.delegate = self
           }
    

    or you can set it in storyboard as enter image description here

    -hence delegates will call as

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

    EDIT: For UISearchController

    var searchController: UISearchController!
    func configureSearchController() {
            // Initialize and perform a minimum configuration to the search controller.
            searchController = UISearchController(searchResultsController: nil)
            searchController.searchResultsUpdater = self
            searchController.dimsBackgroundDuringPresentation = false
            searchController.searchBar.placeholder = "Search here..."
            searchController.searchBar.delegate = self
            searchController.searchBar.sizeToFit()
    
            // Place the search bar view to the tableview headerview.
            tblSearchResults.tableHeaderView = searchController.searchBar
        }