1

I am trying to autofocus a searchbar when i click on a bar button, but it does not seem to work with becomeFirstResponder, follow the GIF:

Example

I've already tried using becomeFirstResponder and it does not work, this is how i am handling the searchbar:

// MARK: SearchBar Delegate
    @IBAction func showSearchBarAction(_ sender: Any) {
        let searchController = UISearchController(searchResultsController: nil)
        searchController.searchBar.delegate = self
        searchController.searchResultsUpdater = self
        searchController.searchBar.keyboardAppearance = .dark
        searchController.dimsBackgroundDuringPresentation = false
        navigationItem.searchController = searchController
        navigationItem.searchController?.isActive = true
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        navigationItem.searchController?.isActive = false
        self.navigationItem.searchController = nil
    }

All of it works perfectly, but the autofocus is something i really want and i can't change my design as well

Solution

This code is the solution:

Example

This is how my class declaration looks like:

class YourViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate, UISearchControllerDelegate {
// MARK: SearchBar Delegate
    @IBAction func showSearchBarAction(_ sender: Any) {
        let searchController = UISearchController(searchResultsController: nil)
        searchController.delegate = self
        searchController.searchBar.delegate = self
        searchController.searchResultsUpdater = self
        searchController.searchBar.keyboardAppearance = .dark
        searchController.dimsBackgroundDuringPresentation = false
        self.navigationItem.searchController = searchController
        self.navigationItem.searchController?.isActive = true
    }

    func didPresentSearchController(_ searchController: UISearchController) {

        DispatchQueue.main.async {
            searchController.searchBar.becomeFirstResponder()
        }
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        navigationItem.searchController?.isActive = false
        self.navigationItem.searchController = nil
    }
Breno Prata
  • 712
  • 5
  • 10
  • 1
    https://stackoverflow.com/questions/27951965/cannot-set-searchbar-as-firstresponder – cora Sep 06 '19 at 15:27
  • Sometimes it's just because the keyboard does not show when you run the Simulator. Check by toggling the software keyboard: hit command+K when you think the keyboard should be displayed (Hardware -> Keyboard -> Toggle Software Keyboard in Simulator). – David Steppenbeck Sep 06 '19 at 16:04
  • I've built it on my iphone and the same happens :( – Breno Prata Sep 06 '19 at 17:26
  • Thank you so much cora and David, i found the answer, i'll update the question with the solution – Breno Prata Sep 06 '19 at 17:40

0 Answers0