Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable/enable UISearchBar keyboard's Search button?

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

like image 694
Confused Avatar asked Mar 15 '12 14:03

Confused


3 Answers

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.

like image 50
MishieMoo Avatar answered Nov 03 '22 21:11

MishieMoo


Short answer is no...

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

like image 44
Alladinian Avatar answered Nov 03 '22 23:11

Alladinian


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.

like image 29
Hitesh Surani Avatar answered Nov 03 '22 21:11

Hitesh Surani