I have a searchBar I'm setting in a tableviewcontroller. i've referenced this similar question UISearchBar cannot become first responder after UITableView did re-appear but am still unable to set it as first responder. In .h file:
@property (strong, nonatomic) UISearchController *searchController;
@property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
In view didload:
self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.hidesNavigationBarDuringPresentation = NO;
self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
self.tableView.tableHeaderView = self.searchController.searchBar;
And in viewDidAppear:
-(void)viewDidAppear:(BOOL)animated {
[self.searchController setActive:YES];
[self.searchController.searchBar becomeFirstResponder];
[super viewDidAppear:animated];
}
When I segue to the view the searchBar animates, but no keyboard appears.
The function
searchController.searchBar.becomeFirstResponder()
must be called in the main thread and aftersearchController.active = true
in the viewDidLoad method. Here're the full solution. It works on iOS 9.3Very similar to other answers, but I had to access the main queue in the
ViewDidAppear
. TheSearchBarController
can't be acted upon until theView
appears and then can only be done so in the main queue forUI
:Based on @mislovr's solution, the
0.1
delay was not long enough. Here is my updated code to that answer.To me, there’s a quite big lag when using
viewDidAppear
. It can be better to usebecomeFirstResponder
asynchronously inviewDidLoad
(tested with iOS 10, Swift 3):Swift 4, iOS 11
It works for me
This is what it worked for me in Swift 3.