Swift iOS-如何让键盘在呈现SearchController的同一时间呈现自己?

时间:2018-07-31 17:30:18

标签: ios swift uisearchcontroller uikeyboard

就上下文而言,我的键盘成功出现了,所以这不是问题。

我有一个searchButton作为rightBarButtonItem,当按下它时会模态显示一个包含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) 
}

SearchController:  我已经尝试在searchController.isActive = truesearchController.searchBar.becomeFirstResponder() r的DispatcQeue.main的{​​{1}}中添加viewWillAppearviewDidAppea,但没有区别

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()
    }
}

}

2 个答案:

答案 0 :(得分:1)

确定有一个延迟。动画完成后,出现键盘。

 present(nav, animated: true, completion: nil) 

答案 1 :(得分:0)

请尝试这个。 如果您不使用动画预设视图控制器,它将立即打开键盘,但是如果我们提供视图控制器动画,则它将在当前动画完成后打开键盘。 谢谢。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(true)
    DispatchQueue.main.async {
        self.searchController.searchBar.becomeFirstResponder()
    }
}