如何在显示searchController时自动显示键盘

时间:2017-06-16 17:47:49

标签: ios swift button uisearchbar uisearchcontroller

@IBAction func MapSearchController(_ sender: UIBarButtonItem) {

    let searchTable = storyboard!.instantiateViewController(withIdentifier: "SearchTableViewController") as! SearchTableViewController

        mapSearchController = UISearchController(searchResultsController: searchTable)
        mapSearchController.searchResultsUpdater = searchTable
        present(mapSearchController!, animated: true, completion: nil)
        mapSearchController.searchBar.becomeFirstResponder()
        self.mapSearchController.dimsBackgroundDuringPresentation = true
        self.mapSearchController.searchBar.sizeToFit()
        self.mapSearchController.searchBar.barTintColor = UIColor.black
        self.mapSearchController.searchBar.placeholder = "חפש ברים"
        self.mapSearchController.hidesNavigationBarDuringPresentation = true
        mapSearchController.searchBar.delegate = self
        definesPresentationContext = true
        searchTable.mapView = mapView
        searchTable.handleMapSearchDelegate = self

如何在显示searchController时自动显示键盘?我尝试了很多解决方案,但没有一个能为我工作..包括becomeFirstResponder()等......请帮忙

3 个答案:

答案 0 :(得分:2)

问题是,当加载视图ID时,不会显示搜索控制器,因此即使在使用eventFirstResponder之后也无法解决问题。下面的代码将解决问题,并在搜索栏中用光标打开键盘。

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

答案 1 :(得分:0)

首先,移动:

present(mapSearchController!, animated: true, completion: nil)

到最后,在完成mapSearchController上的所有属性设置后。

然后确保添加委托方法:

func didPresentSearchController(_ searchController: UISearchController) {
  searchController.searchBar.becomeFirstResponder = true
}

如果仍然无效,请确保此VC符合搜索UISearchControllerDelegate。

答案 2 :(得分:0)

你设置得太早了。此时,您的viewDidLoad实例的MapSearchController尚未触发。 becomeFirstResponder之后您只能viewDidLoad

所以你需要做的是:在becomeFirstResponder的{​​{1}}中设置viewDidAppear