让搜索栏成为第一响应者

时间:2017-01-15 01:40:30

标签: swift3 uisearchbar uisearchcontroller

我在UISearchController内有一个UINavigationBar。用户必须点击UIBarButtonItem,我会在其中实例化新的UIViewController,然后展示它,以便开始搜索。

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
  }

}

我已经做了大量的研究,但仍然无法找到解决方案......

帮助使搜索控制器成为第一个响应者将非常感激。

1 个答案:

答案 0 :(得分:12)

使UISearchBar主线程上的第一个响应者是solution

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

  DispatchQueue.main.async {
    self.searchController.searchBar.becomeFirstResponder()
  }
}