Question

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];
Was it helpful?

Solution 2

After long searching I found Error. Somewhere in storyboard old connection for UISearchBar with the name mySearchbar was left. Another thing that I had to correct was that the method

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar;

returned NO, every time I went back to previous Controller. But it should return YES to be able to set focus on search bar next time.

OTHER TIPS

Try this

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

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

Was strugling with the same - had a UISearchBar inside a UITextView's keyboard accessory and even after [self.searchBar becomeFirstResponder] was called, keyboard input was still received by the text view.

This is what finally helped:

[self.searchBar.window makeKeyAndVisible];

Apparently the keyboard accessory is part of a different UIWindow than the UITextField.

Note: To continue typing in the text view, you should then call something like [self.textView.window makeKeyAndVisible]; ...

Have you tried adding self.mySearchBar.delegate = self;

You should use strong in your property

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

Always set strong in your property for IBOutlet. When you pop B from navigationController, mySearchBar has released, so you push back to B, [self.mySearchBar becomeFirstResponder] is not work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top