Created
July 7, 2011 19:53
-
-
Save jeksys/1070394 to your computer and use it in GitHub Desktop.
Detecting when clear is clicked in UISearchBar (X button)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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; | |
} |
Does not work for iOS 8
does not work
Doesn't work.
Doesn't work anymore.
doesn't work
Doesn't work
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.
doesn't work
this works!
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if (searchText.length == 0){
[searchBar performSelector:@selector(resignFirstResponder)
withObject:nil
afterDelay:0];
}
}
@astramex19 code works like a charm ! Thanks !
doesn't work
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
doesnt work