Search code examples
iphoneiosuisearchbarfirst-responder

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).


Solution

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