Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 339
Kevin Mann Avatar asked Oct 24 '16 23:10

Kevin Mann


2 Answers

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.

like image 174
NicolasElPapu Avatar answered Oct 04 '22 18:10

NicolasElPapu


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

like image 22
user3189586 Avatar answered Oct 04 '22 20:10

user3189586