Gordon Glas
Gordon Glas

Reputation: 1699

UISearchBar becomeFirstResponder returns 0, but have valid reference to UISearchBar

I have a UIViewController with UISearchBar (and SearchDisplayController) along with a UITableView. When navigating to this view controller, I want to auto-focus on the UISearchBar (bring up the keyboard with focus on the text field in the search bar). Everything says to use

[searchBar becomeFirstResponder]

(assuming searchBar is an outlet to the UISearchBar)

I put this at the end of viewDidLoad:

- (void)viewDidLoad
{
    [super viewDidLoad];

    BOOL did = [searchBar becomeFirstResponder];

    [searchBar setText:@"donkey"];
}

Variable did is 0 (and focus doesn't happen), but the search bar's text is successfully changed to donkey.

What am I doing wrong?

I'm using iOS 5 with ARC and latest Xcode (4.3.2).

Upvotes: 1

Views: 4526

Answers (4)

cl0sure
cl0sure

Reputation: 21

we must ensure the METHOD becomeFirstResponder be performed on mainThread so make it like :

[xxx performSelectorOnMainThread:@selector(becomeFirstResponder) withObject:nil waitUntilDone:NO];

Upvotes: 2

Scott Loomis
Scott Loomis

Reputation: 69

This worked for me:

[window makeKeyAndVisible]

Upvotes: 2

Javen.Yang
Javen.Yang

Reputation: 181

add your code to -(void)viewDidAppear;

Upvotes: 3

Gordon Glas
Gordon Glas

Reputation: 1699

Got it working. Just had to put it in viewDidAppear instead of viewDidLoad or viewWillAppear.

Upvotes: 9

Related Questions