iosswiftuisearchbar

How to recognize a click on the X button of the UISearchBar?


I have to change a boolean variable value when the user clears the word that he was searching for. He clears it when he taps the X icon on the right side of the search bar.

I don't know how to get this action. The functions related to search bar only recognizes clicks on the cancel button, bookmarks button and search results button.

How can I do that using Swift 2 on iOS9 devices?


Solution

  • You can implement this delegate function of UISearchBarDelegate:

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
      if  searchText.count == 0 {
        //call your func
      }
    }
    

    as the documentation says:

    Discussion This method is also invoked when text is cleared from the search text field.