Archive for April, 2011

Detecting when clear is clicked in UISearchBar (X button)

When conforming to UISearchBar delegate we do not get a notification when user clicks the clear text button in the UISearchBar. However, UISearchBar has a subview of type UITextField, and if we conform to UITextFieldDelegate we do get a call when clear text button is clicked in form of:

- (BOOL)textFieldShouldClear:(UITextField *)textField

The problem is that when we conform to UISearchBar protocol, we do not conform to the underlying UITextField’s delegate. What we have to do is set the delegate ourselfs in for example viewDidLoad method. (if you do not have an outlet to the UISearchBar create it, and call it searchBar).

In your header (.h) file do not forget to conform to delegates.
<UISearchBarDelegate, UITextFieldDelegate>

- (void)viewDidLoad {
  //find the UITextField view within searchBar (outlet to UISearchBar)
  //and assign self as delegate
  for (UIView *view in searchBar.subviews){
    if ([view isKindOfClass: [UITextField class]]) {
      UITextField *tf = (UITextField *)view;
      tf.delegate = self;

- (void)searchBarCancelButtonClicked:(UISearchBar *) aSearchBar {
	[aSearchBar resignFirstResponder];

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    //if we only try and resignFirstResponder on textField or searchBar,
    //the keyboard will not dissapear (at least not on iPad)!
    [self performSelector:@selector(searchBarCancelButtonClicked:) withObject:self.searchBar afterDelay: 0.1];
    return YES;