UISearchBar x button pressed

Fabio picture Fabio · Mar 19, 2015 · Viewed 29.8k times · Source

How handle the event when press the 'x' button?

I try this method but not works.

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{

}

enter image description here

Answer

Eric Johnson picture Eric Johnson · Dec 1, 2015

I don't think there's an easy way to hook into the X button.

However, you can hook into its direct consequence: cleared text.

Try this:

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    if searchText == "" {
        print("UISearchBar.text cleared!")
    }
}

The side effect is this also gets called when you manually clear your text.