Swift: Search bar created at Auto Focus

2020-03-27 10:42发布

问题:

I am creating a table view and a search bar by clicking on a button.But I need the search bar to appear at Auto Focus ( where the user enters text immediately with no need to click inside the search bar). How can I do that ?

回答1:

try this

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


回答2:

This should do it.

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

...

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