Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Search Bar Become First Responder

I have a UISearchController inside of a UINavigationBar. The user has to tap on a UIBarButtonItem, in which I instantiate a new UIViewController then present it, in order to begin searching.

class ViewController: UIViewController {

  var searchController: UISearchController! 

  override func viewDidLoad() {
    super.viewDidLoad()
    setupSearchController()
  }

  func setupSearchController() {
    searchController = UISearchController(searchResultsController: nil)
    searchController.searchBar.delegate = self
    searchController.searchResultsUpdater = self
    searchController.searchBar.showsCancelButton = true
    searchController.dimsBackgroundDuringPresentation = false
    searchController.hidesNavigationBarDuringPresentation = false

    definesPresentationContext = true
    navigationItem.titleView = searchController.searchBar
  }

}

I've done plenty of research before hand, but still can't manage to find a solution...

Help in making the search controller become the first responder would be very much appreciated.

like image 914
dispatchswift Avatar asked Jan 15 '17 01:01

dispatchswift


1 Answers

Making the UISearchBar the first responder on the main thread was the solution.

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

  DispatchQueue.main.async {
    self.searchController.searchBar.becomeFirstResponder()
  }
}
like image 131
dispatchswift Avatar answered Oct 28 '22 07:10

dispatchswift