Skip to content

Instantly share code, notes, and snippets.

@jeksys
Created July 7, 2011 19:53
Show Gist options
  • Save jeksys/1070394 to your computer and use it in GitHub Desktop.
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;
}
@CavalcanteLeo
Copy link

doesnt work

@chuangeezy
Copy link

Does not work for iOS 8

@EvgenyKarkan
Copy link

does not work

@victorgdb
Copy link

Doesn't work.

@marcelojunior7
Copy link

Doesn't work anymore.

@cprovatas
Copy link

doesn't work

@VaishnaviRathod
Copy link

Doesn't work

@gfpoliva
Copy link

gfpoliva commented Jan 8, 2018

The reason why this doesn't work is because now UISearchBar have a UIView that encapsulates its components.
I think this is an unsafe way to detect clear tap in UISearchBar because Apple can change the way UIKit componentes are architected.

@lucasw-99
Copy link

doesn't work

@astramex19
Copy link

astramex19 commented Jul 4, 2018

this works!

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

if (searchText.length == 0){
[searchBar performSelector:@selector(resignFirstResponder)
                            withObject:nil
                            afterDelay:0];
}
}

@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