Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide keyboard when losing focus off UISearchBar

I'm not sure why this is so hard. I have a UISearchBar at the top of my page. When the user types into that UISearchBar, it will automatically filter the results in the UITableView that is below the search bar. There is no need for a Search button since I search when keys are pressed.

The flow of the application is that the user types a search in the search bar (with the keyboard being displayed) and then will scroll the results in the table view - at which point the keyboard needs to disappear.

I'm having a hard time getting the keyboard to disappear.

I know I need to do:

    [searchBar resignFirstResponder];

to get the keyboard to disappear but I can't find what delegate I need to perform this on. I want to do this as soon as the user touches the table view.

Any ideas?

like image 287
rein Avatar asked May 20 '09 14:05

rein


3 Answers

Try this:

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];

    [searchBar resignFirstResponder];

}

It worked for me

like image 52
H Vargas Avatar answered Nov 09 '22 06:11

H Vargas


I think the easiest (and best) way to do this is to subclass your global view and use hitTest:withEvent method to listen to any touch. Touches on keyboard aren't registered, so hitTest:withEvent is only called when you touch/scroll/swipe/pinch... somewhere else, then call [self endEditing:YES].

This is better than using touchesBegan because touchesBegan are not called if you click on a button on top of the view. It is also better than using a dim screen because in a complexe and dynamic user interface, you can't put dim screen every where. Also, it's better than calling [searchBar resignFirstResponder], because you may have many text fields on screen, so this works for all of them.

like image 2
Enzo Tran Avatar answered Nov 09 '22 06:11

Enzo Tran


You might want to do it as Cydia (jailbroken packaging UI) does it - there is a search button, and when you press the search button, it closes the keyboard. The results are still filtered as you type for a preview.

like image 1
Isaac Waller Avatar answered Nov 09 '22 06:11

Isaac Waller