1
votes

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

4
BOOL did =[self.searchDisplayController.searchBar becomeFirstResponder]; and set the delegteDeepesh
What do you mean set delegate? Do I need to implement a callback? Tried returning YES in searchBarShouldBeginEditing: but that didn't work. Not obvious which one I need to implement. ThanksGordon Glas
Btw, delegates are already set to the UIViewController for both the UISearchBar and Search Display Controller.Gordon Glas

4 Answers

9
votes

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

3
votes

add your code to -(void)viewDidAppear;

2
votes

This worked for me:

[window makeKeyAndVisible]
2
votes

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

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