我在让我的搜索控制器中的搜索栏成为firstResponder时遇到一些困难。我注意到没有调用委托方法,但是当我键入以过滤用户列表时,搜索栏会按预期工作。
searchcontroller的定义:
private func setupSearchController() {
self.navigationItem.searchController = searchController
searchController.definesPresentationContext = true
searchController.delegate = self
searchController.isActive = true
searchController.searchBar.delegate = self
searchController.searchBar.becomeFirstResponder()
}
设置:
func didPresentSearchController(searchController: UISearchController) {
UIView.animate(withDuration: 0.1, animations: { () -> Void in }) { (completed) -> Void in
searchController.searchBar.becomeFirstResponder()
}
}
我尝试了另一个SO问题的建议,但未调用委托方法:
MainComponent.js
答案 0 :(得分:0)
问题是您试图在UI完全加载之前访问UI元素(searchbarcontroller)。 这可以通过2种方式完成
使用主队列显示键盘
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
中在viewDidAppear中显示键盘
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.searchController.searchBar.becomeFirstResponder()
}
使用这种方法时,只要屏幕出现,总是会显示键盘。