Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The UISearchBar doesn't dismiss the keyboard when enter is pressed

The UISearchBar doesn't dismiss the keyboard when enter is pressed, or the user touch somewhere else.

I need to use the remove keyboard button on the bottom right of the iOS keyboard in order to remove the keyboard and invoke:

- (void)searchBarTextDidEndEditing:(UISearchBar *)aSearchBar

How can I fix it?

like image 956
aneuryzm Avatar asked Sep 28 '12 08:09

aneuryzm


4 Answers

- (void)searchBarTextDidEndEditing:(UISearchBar *)aSearchBar {
    [aSearchBar resignFirstResponder];
}

Also you have to set delegate for the UISearchBar: UISearchBarDelegate

It should work.

Here is sample code http://developer.apple.com/library/ios/#samplecode/ToolbarSearch/Listings/ToolbarSearch_APLToolbarSearchViewController_m.html#//apple_ref/doc/uid/DTS40009461-ToolbarSearch_APLToolbarSearchViewController_m-DontLinkElementID_9

Another option is searchBarSearchButtonClicked we can use.

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    // You can write search code Here
}
like image 57
Kamleshwar Avatar answered Nov 18 '22 17:11

Kamleshwar


Add UISearchBarDelegate in .h

Also set SearchBar's object delegate to self.

you should do add UISearchBarDelegate's method:

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

EDIT : Above doesnot work then add this:

[self.view endEditing:YES];
like image 24
Paresh Navadiya Avatar answered Nov 18 '22 17:11

Paresh Navadiya


for swift 1.2 keyboard will hide when you click finished , and there is another function for cancel but it's not good to use it as when the user click cancel he might want to search for another word ...

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
    }
like image 3
Mostafa Sultan Avatar answered Nov 18 '22 19:11

Mostafa Sultan


Use the following code snippet to close/hide the keyboard when return button is clicked.

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 
{

    if([text isEqualToString:@"\n"])
    {        
        [searchBar resignFirstResponder];
        return NO;
    }
        return YES;
}
like image 2
Bharath Avatar answered Nov 18 '22 19:11

Bharath