我有一些困难,让搜索栏在我searchcontroller成为firstResponder。我注意到没有被称为委托方法,但是当我打字筛选用户的列表搜索栏按预期工作。
searchcontroller的定义:
lazy var searchController: UISearchController = {
let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search"
return searchController
}()
设置它:
private func setupSearchController() {
self.navigationItem.searchController = searchController
searchController.definesPresentationContext = true
searchController.delegate = self
searchController.isActive = true
searchController.searchBar.delegate = self
searchController.searchBar.becomeFirstResponder()
}
我试图从另一个这项建议SO问题,但委托方法不被称为:
func didPresentSearchController(searchController: UISearchController) {
UIView.animate(withDuration: 0.1, animations: { () -> Void in }) { (completed) -> Void in
searchController.searchBar.becomeFirstResponder()
}
}
问题是你试图访问UI元素(searchbarcontroller)之前,用户界面是完全加载。这可以通过两种方式来完成
private func setupSearchController() {
self.navigationItem.searchController = searchController
searchController.definesPresentationContext = true
searchController.delegate = self
searchController.isActive = true
searchController.searchBar.delegate = self
DispatchQueue.main.async {
self.searchController.searchBar.becomeFirstResponder()
}
}
采用这种方法键盘将只显示在viewDidLoad中一次
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.searchController.searchBar.becomeFirstResponder()
}
通过这种方法,键盘会始终显示时画面出现。