Skip to content

Instantly share code, notes, and snippets.

@jeksys
Created July 7, 2011 19:53
Show Gist options
  • Select an option

  • Save jeksys/1070394 to your computer and use it in GitHub Desktop.

Select an option

Save jeksys/1070394 to your computer and use it in GitHub Desktop.
Detecting when clear is clicked in UISearchBar (X button)
- (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;
break;
}
}
}
- (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;
}
@jasson-33
Copy link

@astramex19 code works like a charm ! Thanks !

@qountmobile
Copy link

doesn't work

@fahadjamal
Copy link

fahadjamal commented Aug 13, 2021

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    searchBar.searchTextField.delegate = self
}

func textFieldShouldClear(_ textField: UITextField) -> Bool {
    print("textFieldShouldClear")
    return true
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment