Kevin Mann
Kevin Mann

Reputation: 741

UISearchBar searchBarCancelButtonClicked not being called using Swift 3

For some reason when I click the circle x cancel button in a UISearchBar the searchBarCancelButtonClicked event is not firing, it worked in a swift 2 project but not in this swift 3 one.

I am now extending my view controller instead of the inline class way but I believe that is working as the searchBarSearchButtonClicked event does work. Here is what I have so far:

extension MyViewController: UISearchBarDelegate {
   func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
      print("here?")
      searchBar.resignFirstResponder()
      handleCancelSearch()
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        if let searchText = searchBar.text {
            performSearchUsing(term:searchText)
        }

    }
}

The print is not logged and the function not called. Am I missing something silly?

Upvotes: 8

Views: 5362

Answers (2)

NicolasElPapu
NicolasElPapu

Reputation: 1676

Maybe you are missing something silly as I did, the "circle x" is not actually the cancel button, and I thought that too, the cancel button comes disabled by default, you can activate it via storyboard on the attributes of the searchBar or you can do it programmatically with:

searchBar.showsCancelButton = true

After that, the method should work.

Upvotes: 5

user3189586
user3189586

Reputation: 125

If any one still looking for the option how act on "X" button. use below method which is available in

UISearchBarDelegate 

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
{
    if searchText.count == 0
    {   // Hide content

    }
}

Note : it is not cannel button its clear text button which is visible after typing something in searchBar

Upvotes: 1

Related Questions