6

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 ?

Youssef Emad
  • 319
  • 2
  • 13

3 Answers3

17

try this

@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
    super.viewDidLoad()
    searchBar.becomeFirstResponder()
}
yoAlex5
  • 29,217
  • 8
  • 193
  • 205
3

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()
   }
}
Tim Walsh
  • 1,089
  • 11
  • 27
2

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()
    }
}