10

I am using UISearchBar in my code. I have imported its delegate in header file and implemented some delegate methods in implementation file also.

When we tap on the UISearchBar, a keyboard will appear to enter text. The return key of the keyboard is "Search" button. It will disabled by default. When we enter a character, It will get enabled. (Am I right?)

Here the problem comes.. I want to enable the UISearchBar keyboard's return key when the user types atleast two letters.

Is it possible? If yes, how can we do it?

Thanks

Confused
  • 3,846
  • 7
  • 45
  • 72

7 Answers7

9

You can't disable the search button. What you can do is use the UISearchBarDelegate methods to figure out if you should take action on the search button being clicked, like so:

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    if (searchBar.text.length < 2) {
        return;
    }
    else {
        // Do search stuff here
    }
}

The Apple Documentation for this is very useful as well, and is a great starting point for customizing the searchBar's behavior.

MishieMoo
  • 6,620
  • 2
  • 25
  • 35
1

You can do it by accessing UISearchBar property.

let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.enablesReturnKeyAutomatically = false

By playing with enablesReturnKeyAutomatically property you can achieve your requirements.

Thanks.

Hitesh Surani
  • 12,733
  • 6
  • 54
  • 65
1

Here is the setting you're looking for:

searchBar.enablesReturnKeyAutomatically = true

Volodymyr Kulyk
  • 6,455
  • 3
  • 36
  • 63
1

Short answer is no...

Longer, hackier and more exotic one is here: How to disable/enable the return key in a UITextField?

Community
  • 1
  • 1
Alladinian
  • 34,483
  • 6
  • 89
  • 91
  • For specifically "Can I literally disable return key for searchbar", this is the correct answer. Except that OP's requirement could be fulfilled otherwise – NSNoob Dec 16 '15 at 09:50
0

This is how i do it:

    if([searchbar.text length] == 0) {
        [searchBar performSelector: @selector(resignFirstResponder)
                           withObject: nil
                           afterDelay: 0.1];
    }
Dev2rights
  • 3,469
  • 3
  • 25
  • 42
Dhiraj Umale
  • 92
  • 1
  • 7
0

You can try this,

 - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{
       if (searchText.length>=2) {
         [Main_SearchBar resignFirstResponder];

         // Do your code here
       }
}
Kupendiran iOS
  • 217
  • 2
  • 5
-1

You can try this

if([self.searchBar.text length] > 2)
{
    [self.searchBar resignFirstResponder];
}
Krunal
  • 1,318
  • 1
  • 13
  • 31