Swift:在Auto Focus中创建的搜索栏

时间:2015-08-03 11:28:03

标签: swift search uisearchcontroller autofocus

我正在通过单击按钮创建表格视图和搜索栏。但是我需要搜索栏显示在自动聚焦(用户立即输入文本而不需要在搜索栏内单击)。我怎么能这样做?

3 个答案:

答案 0 :(得分:10)

试试这个

 @IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() 
{
        super.viewDidLoad()
searchBar.becomeFirstResponder()
}

答案 1 :(得分:1)

Swift 5.2

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    searchController.isActive = true
}

override func viewDidLoad() {
    super.viewDidLoad()
    searchController.delegate = self
}

extension ViewController: UISearchControllerDelegate {
    func didPresentSearchController(_ searchController: UISearchController) {
        searchController.searchBar.becomeFirstResponder()
    }
}

答案 2 :(得分:0)

这应该这样做。

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    searchController.active = true
}

...

extension GDSearchTableViewController: UISearchControllerDelegate {
   func didPresentSearchController(searchController: UISearchController) {
      searchController.searchBar.becomeFirstResponder()
   }
}