只是为了上下文,我的键盘成功出现了,所以这不是问题所在。
我有一个searchButton作为我的右BarButtonItem,当按下它时,它会以模式显示一个包含SearchController的vc。当SearchController出现时,键盘也会出现,但键盘出现晚了一秒钟,在它出现之前大约有1秒的延迟。基本上,vc出现在场景中,然后键盘出现,我不能让键盘在出现SearchController的同时出现。我在YouTube和Vimeo的iOS应用程序上,当我按下他们的搜索按钮时,键盘会同时显示SearchController,没有1秒的延迟。
如何让键盘在SearchController显示自己的同时显示自己
模式显示SearchController:的按钮
@objc func searchButtonTapped() {
let searchVC = SearchController()
let nav = UINavigationController(rootViewController: searchVC)
present(nav, animated: true, completion: nil)
}
搜索控制器:我已经尝试过在viewWillAppear
和viewDidAppea
r的DispatcQeue.main
中添加searchController.isActive = true
和searchController.searchBar.becomeFirstResponder()
,但没有区别
class SearchController: UIViewController {
var searchController: UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self
searchController.searchBar.delegate = self
searchController.searchResultsUpdater = self
searchController.searchBar.showsCancelButton = true
searchController.searchBar.placeholder = "Search"
searchController.searchBar.returnKeyType = .search
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.sizeToFit()
searchController.searchBar.tintColor = UIColor.black
definesPresentationContext = true
navigationItem.hidesBackButton = true
navigationItem.titleView = searchController.searchBar
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
searchController.isActive = true
}
// I tried both of these searchContrller delegate methods SEPERATELY but it made no difference, there's still a 1 second delay
func presentSearchController(_ searchController: UISearchController) {
DispatchQueue.main.async {
self.searchController.searchBar.becomeFirstResponder()
}
}
func didPresentSearchController(_ searchController: UISearchController) {
DispatchQueue.main.async {
self.searchController.searchBar.becomeFirstResponder()
}
}
}
当然有延迟。。如果此动画完成,则出现键盘。
present(nav, animated: true, completion: nil)
请尝试一下。如果您不使用动画预设视图控制器,它将立即打开键盘,但如果我们呈现视图控制器动画,它将在当前动画完成后打开键盘。谢谢
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
DispatchQueue.main.async {
self.searchController.searchBar.becomeFirstResponder()
}
}