Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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];
like image 886
zyxel Avatar asked Sep 11 '13 23:09

zyxel


3 Answers

Try this

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

-(void)setCorrectFocus 
{
     [self.mySearchBar becomeFirstResponder];
}
like image 147
Asanka Madushan Avatar answered Oct 23 '22 22:10

Asanka Madushan


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.

like image 24
zyxel Avatar answered Oct 23 '22 21:10

zyxel


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]; ...

like image 45
frenya Avatar answered Oct 23 '22 21:10

frenya