views:

117

answers:

2

Hi There,

I'm writing for iphone OS 3.1.3. I want the search button in the keyboard from my UISearchBar to have the search button enabled all the time. If this was any old UITextField (not a search bar) the property would be enablesReturnKeyAutomatically.

I have tried setting this using the example given at http://discussions.apple.com/thread.jspa?messageID=8457910

which suggests:

UITextField *searchTextField ; 
searchTextField = [[searchBar subviews]objectAtIndex:0];
searchTextField.enablesReturnKeyAutomatically = NO ;

Should work.

unfortunately it crashes:

2010-05-20 08:36:18.284 ARemote[5929:207] *** -[UISearchBarBackground setEnablesReturnKeyAutomatically:]: unrecognized selector sent to instance 0x3b31980
2010-05-20 08:36:18.284 ARemote[5929:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[UISearchBarBackground setEnablesReturnKeyAutomatically:]: unrecognized selector sent to instance 0x3b31980'

I have also tried

((UITextField *)[(NSArray *)[searchBar subviews] objectAtIndex:0]).enablesReturnKeyAutomatically = NO;</code>

Which gives similar results.

Any ideas?

Cheers Erik

+3  A: 

You're accessing an the documented view hierarchy of UISearchBar. This may be lead to rejection, but your app's behavior will be unspecified on firmware upgrade.

This is an example. When that reply was posted, the UITextField was still the 1st subview of the search bar. Now the 1st subview becomes UISearchBarBackground.

The minimal change is to iterate through the whole view hierarchy and find the actual UITextField.

for (id subview in searchBar.subviews) {
   if ([subview respondsToSelector:@selector(setEnablesReturnKeyAutomatically:)]) {
      [subview setEnablesReturnKeyAutomatically:NO];
      break;
   }
}

But for forward compatibility, it's better to use a UITextField instead of a UISearchBar, or not to demand the search button be enabled all the time (e.g. use the Cancel button).

KennyTM
A: 

Really useful!!!!!

Sagar Mane