I\'m using the UISearchBar (but not the SearchDisplayController that\'s typically used in conjunction) and I\'d like to dismiss the keyboard when you hit the \'X\' button.
Updated for SWIFT 3:
Suppose that the user has entered a string in searchfield and clicks x the following code works to hide keyboard when x is pressed
`
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
{
if searchBar.text == nil || searchBar.text == ""
{
searchBar.perform(#selector(self.resignFirstResponder), with: nil, afterDelay: 0.1)
}
}
`
Another point of view for clear text flow (similar to @TomSwift answer but clearer for me and less tricky). Also, I need to hide Cancel button after exit from the search bar, implement live search (after each symbol) and cover table before user complete search.
//self.searchHoverView can cover table view
//performSearchWithSearchBar: method for performing search
#pragma mark - UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
[searchBar setShowsCancelButton:YES animated:YES];
self.searchHoverView.hidden = NO;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if (searchText.length) {
[self performSearchWithSearchBar:searchBar];
} else {
UIButton *button;
for (UIView *subView in [searchBar subviews]) {
for (UIView *view in [subView subviews]) {
if ([view isKindOfClass:[UIButton class]]) {
button = (UIButton *)view;
break;
}
}
}
if (button) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[button sendActionsForControlEvents:UIControlEventTouchUpInside];
});
}
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
self.searchBar.text = nil;
[self.searchBar setShowsCancelButton:NO animated:YES];
[self.searchBar resignFirstResponder];
self.searchHoverView.hidden = YES;
}