让搜索栏成为第一响应者

Make Search Bar Become First Responder

我在 UINavigationBar 里面有一个 UISearchController。用户必须点击一个 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
  }

}

我事先做了很多研究,但仍然无法找到解决方案...

帮助使搜索控制器成为第一响应者将不胜感激。

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

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

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