On the UISearchBar, there's an X element that allows you to clear all of the contents at once. Is there a way to get notified when this happens?
UISearchBarDelegate::searchBarCancelButtonClicked
is fired only when the "Cancel" button is tapped.
On the UISearchBar, there's an X element that allows you to clear all of the contents at once. Is there a way to get notified when this happens?
UISearchBarDelegate::searchBarCancelButtonClicked
is fired only when the "Cancel" button is tapped.
I had the same issue and I solved this issue by using this function.
Here is "Method Swizzling" solution.
UISearchBar
. This category create a new method and swizzle method between-(BOOL)textFieldShouldClear:(UITextField *)textField;
and-(BOOL)jbm_textFieldShouldClear:(UITextField *)textField
in runtime.UISearchBarDelegate
in order to add a new method- (void)searchBarClearButtonClicked:(id)sender;
UISearchBar+JMBTextFieldControl.h
UISearchBar+JMBTextFieldControl.m
Reference
Dave DeLong - How to add a method to an existing protocol in Cocoa?
Nikolay Vlasov - CCBottomRefreshControl
The
UISearchBar
doesn't have a delegate method for this event. You can nearly get what you want by implementing thetextDidChange:
method of the callback delegate and checking for an empty string.I don't recommend it, but there is another possible way. The
UISearchBar
is composed of a UITextField, which does have a delegate method that is called when the user taps the clear button (textFieldShouldClear:
). You can get theUITextField
by traversing theUISearchBar
's child views:(this is in the context of a derived
UISearchBar
class)from here, you could re-assign the
UITextField
delegate to your own implementation, taking care to forward delegate calls to the old delegate. This way you could intercepttextFieldShouldClear:
. Or if it turns out theUISearchBar
is the delegate for theUITextField
it contains you could swizzle the call to textFieldShouldClear:... Not ideal, clearly, but technically feasible.Here is an answer from a previous question, this should do exactly what you want. UISearchbar clearButton forces the keyboard to appear