@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()等等。。。请帮忙

最佳答案

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

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

10-05 20:22