Show keyboard automatically when UISearchController is loaded

。_饼干妹妹 提交于 2019-12-03 03:10:59
Nikita Leonov

BecomeFirstResponder is the way to go, but you should do it not in viewDidLoad. Look at following discussion for details - Cannot set searchBar as firstResponder

I also tried the suggestions listed in the link mentioned by Nikita Leonov. I needed to add make the class a UISearchControllerDelegate & UISearchBarDelegate and then it worked. I don't u

class PickAddressViewController: UITableViewController, UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.mySearchController = ({
            controller.searchBar.delegate = self
        })()

        self.mySearchController.active = true
        self.mySearchController.delegate = self
    }

    func didPresentSearchController(searchController: UISearchController) {
        self.mySearchController.searchBar.becomeFirstResponder()
    }
    …
}
override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)
    self.navigationItem.titleView = searchController!.searchBar
    dispatch_async(dispatch_get_main_queue(), {
        self.searchController?.active = true
        self.searchController!.searchBar.becomeFirstResponder()
    })
}

and this code

func presentSearchController(searchController: UISearchController) {
    searchController.searchBar.becomeFirstResponder()
}

make sure you give searchController?.delegate = self in viewDidLoad(). Tested on iOS 9.* device

Swift 3 solution in my case:

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.titleView = mySearchController.searchBar
    mySearchController.searchResultsUpdater = self
    mySearchController.delegate = self

}

override func viewDidAppear(_ animated: Bool) {
    DispatchQueue.main.async {
        self.mySearchController.isActive = true
    }
}

func presentSearchController(_ searchController: UISearchController) {
    mySearchController.searchBar.becomeFirstResponder()
}

Besides doing what the other users suggested, I also did the following, and it worked:

searchController.definesPresentationContext = true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!