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 ?
Swift: Search bar created at Auto Focus
Asked Answered
try this
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
searchBar.becomeFirstResponder()
}
Old answer but still worked for me in SwiftUI. –
Guaiacum
2021-07-02, still working in SwiftUI for iOS 14! –
Toxicant
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()
}
}
When using a UISearchController, this is the only thing that worked for me –
Oxalate
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()
}
}
I had to ensure that the call to becomeFirstResponder() happens on the main thread:
DispatchQueue.main.async {
self.searchController.searchBar.becomeFirstResponder()
}
© 2022 - 2024 — McMap. All rights reserved.