Swift: Search bar created at Auto Focus
Asked Answered
D

4

7

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 ?

Disallow answered 3/8, 2015 at 11:28 Comment(0)
J
17

try this

@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
    super.viewDidLoad()
    searchBar.becomeFirstResponder()
}
Jehias answered 16/11, 2015 at 6:46 Comment(2)
Old answer but still worked for me in SwiftUI.Guaiacum
2021-07-02, still working in SwiftUI for iOS 14!Toxicant
F
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()
   }
}
Feints answered 29/2, 2016 at 10:58 Comment(1)
When using a UISearchController, this is the only thing that worked for meOxalate
S
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()
    }
}
Selectee answered 16/5, 2020 at 17:26 Comment(0)
S
1

I had to ensure that the call to becomeFirstResponder() happens on the main thread:

DispatchQueue.main.async {
        self.searchController.searchBar.becomeFirstResponder()
    }
Substratum answered 22/4 at 16:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.