Search code examples
iosswiftuisearchcontrolleruisearchbardelegate

UISearchcontroller Cancel button not working


class PlaceSelectorViewController: UIViewController, GMSAutocompleteResultsViewControllerDelegate, UISearchBarDelegate, UISearchControllerDelegate {

I have UISearchBarDelegate in my class

searchController?.searchBar.delegate = self

and I had set the delegate to Self.

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

But this Delegate call is not working


Solution

  • You need an outleet for your UISearchBar (assuming you're working with Storyboard this is really easy, just drag and drop via Assistant Editor). and that's what you're going to add the delegate to. In case you built programmatically, then that variable is the one that's going to get assigned to the delegate.

    Here's the example code for the Storyboard built

    @IBOutlet weak var searchBar: UISearchBar! (you must see a filled circle at the right of this, otherwise there's no link between Storyboard and this outlet)

    ...

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