UISearchbar keyboard search button Action

Chenggong Jin picture Chenggong Jin · Jul 13, 2013 · Viewed 50k times · Source

I'm using UISearchBar when I input text on UISearchBar the keyboard shows. At that time, keyboard return key is "Search". I want to implement event when I press the keyboard search button. How can I implement the action? On UITextField it has

-(BOOL)textFieldShouldReturn:(UITextField *)textField;

But on UISearchBar it doesn't have return action.

Thank you for your helping.

Answer

Milo picture Milo · Jul 13, 2013

Add UISearchBarDelegate in .h

Also set SearchBar's object delegate to self.

Add this to the UISearchBarDelegate's method:

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    // Do the search...
}

Swift

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