Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Search bar created at Auto Focus

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 ?

like image 986
Youssef Emad Avatar asked Aug 03 '15 11:08

Youssef Emad


3 Answers

try this

@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
    super.viewDidLoad()
    searchBar.becomeFirstResponder()
}
like image 138
Tejveer Sambariya Avatar answered Nov 08 '22 19:11

Tejveer Sambariya


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()
   }
}
like image 36
Tim Walsh Avatar answered Nov 08 '22 20:11

Tim Walsh


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()
    }
}
like image 2
Anton Putra Avatar answered Nov 08 '22 21:11

Anton Putra