Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dismiss keyboard when the UISearch Bar 'Search" button is pressed?

I've implemented a UISearch bar with the searching functionality set up, however when I press the "Search" button on the keyboard that shows up nothing happens. How can I get the keyboard to hide when the "Search" button is pressed while keeping the text in the search bar intact (To keep the search results present)?

like image 475
Christian Gossain Avatar asked Oct 21 '11 21:10

Christian Gossain


People also ask

How do you dismiss a keyboard?

Android devices have a solution; press the physical back button (provided on some mobile phones) or the soft key back button, and it closes the keyboard.

How do I close the keyboard in Swift?

Microsoft SwiftKey does not have a dedicated minimize keyboard button. Instead, if you slide a finger down the keys from top to bottom, your Microsoft SwiftKey Keyboard is minimized.


2 Answers

From Text, Web and Editing Programming Guide for iOS:

To dismiss the keyboard, you call the resignFirstResponder method of the text-based view that is currently the first responder.

So you should do this in your UISearchBarDelegate:

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    // Do the search...
}
like image 79
rob mayoff Avatar answered Nov 10 '22 08:11

rob mayoff


Swift 4
Make sure you have UISearchBarDelegate defined in your UIViewController

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
}

like image 5
ninahadi Avatar answered Nov 10 '22 08:11

ninahadi