Why UISearchBar does not get Focus even after it is set as a first responder?

zyxel picture zyxel · Sep 12, 2013 · Viewed 8.8k times · Source

Why UISearchBar does not get Focus and keyboard does not appear when UIViewController is pushed to navigation controller for the 2nd time? It seems as no element on the whole view has a focus.

MY USE CASE: I have 2 View Controllers: A and B. Transition is A->B. A, B are pushed to navigation controller.

  1. When I show B for the first time focus is set to the searchbar and keyboard appears.OK.
  2. Then I go back to the A. And again from A->B. Now for the second time there is no focus and keyboard does not appear. It is WRONG.

MY CODE: On the B UIViewController IBOutlet connection to the searchbar is created:

@property (weak, nonatomic) IBOutlet UISearchBar *mySearchBar;

Delegate of the mySearchBar is also set. I set focus on the searchbar in B UIViewController in viewDidAppear method:

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];   
    [self performSelector:@selector(setCorrectFocus) withObject:NULL afterDelay:0.2];
}

-(void) setCorrectFocus {
     [self.mySearchBar becomeFirstResponder];
}

Transitions between controllers are done manually in code like this:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"myStoryboard" bundle:nil];
AController *a = [storyboard instantiateViewControllerWithIdentifier:@"A"];
[self.navigationController pushViewController:a animated:NO];

Answer

Asanka Madushan picture Asanka Madushan · Sep 12, 2013

Try this

-(void)viewDidAppear:(BOOL)animated
{
     [super viewDidAppear:animated];   
     [self setCorrectFocus];
}

-(void)setCorrectFocus 
{
     [self.mySearchBar becomeFirstResponder];
}