1

I have configured a UISearchController as follows within viewDidLoad():

let searchController = UISearchController(searchResultsController: nil);
searchController.delegate = self;
searchController.searchResultsUpdater = self;
searchController.searchBar.delegate = self;

self.searchController.isActive = true;
self.searchController.searchBar.becomeFirstResponder();

self.navigationItem.searchController = searchController;

Although I have set isActive and set the searchBar as the firstResponder, the UISearchController is not active when the view appears on the screen. Manually tapping on the field opens it correctly.

Is there a reason in iOS 12 that the isActive and becomeFirstResponder properties are not respected in viewDidLoad?

Jake Chasan
  • 6,290
  • 9
  • 44
  • 90

2 Answers2

3

Not sure what's happening there, but it's unique to the fact it is in the navigation bar.

This seems to do the trick though.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    DispatchQueue.main.async(searchController.searchBar.becomeFirstResponder)
}
Callam
  • 11,409
  • 2
  • 34
  • 32
0

In my case, in iOS 12.x, I just put the becomeFirstResponder() in viewDidAppear, with a bit of delay, 0.1 seconds. Adding such delay guarantees presentation of keyboard.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    self.definesPresentationContext = true

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        self.searchController.searchBar.becomeFirstResponder()
    }
}

I hope this helps.

EDIT: If you're supporting iOS 10, and 11, this answer of mine from the past might help you out. https://stackoverflow.com/a/53264329/3231194

Glenn Posadas
  • 12,555
  • 6
  • 54
  • 95