Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show keyboard automatically when UISearchController is loaded

I created a UISearchController in a table view controller. I segue to this table view controller using a push segue from another view controller. I want the keyboard to show up with the cursor in the search bar as soon as the table view controller is pushed.

I made the search controller active in the viewDidLoad method using

self.mySearchController.active = true

It does make the search controller active but this does not bring up the keyboard nor is the cursor placed in the search bar. I also tried

self.mySearchController.searchBar.becomeFirstResponder()

This line does not seem to have any effect.

How do I bring up the keyboard automatically/programmatically? Below is a more detailed version of my code

class PickAddressViewController: UITableViewController, UISearchResultsUpdating {

var searchText = ""

var mySearchController = UISearchController()

override func viewDidLoad() {
    super.viewDidLoad()

    self.mySearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()
        controller.searchBar.text = self.searchText

        self.tableView.tableHeaderView = controller.searchBar

        return controller
    })()

    self.mySearchController.active = true
    self.mySearchController.searchBar.becomeFirstResponder()
}
like image 399
RookiePro Avatar asked Jun 28 '15 23:06

RookiePro


2 Answers

Swift 5

  1. in viewDidLoad:
searchViewController.delegate = self
  1. in viewDidAppear:
searchViewController.isActive = true

This activates the SearchController

  1. Define a delegate method:
extension MyViewController: UISearchControllerDelegate {
    func didPresentSearchController(_ searchController: UISearchController) {
        DispatchQueue.main.async {
            searchController.searchBar.becomeFirstResponder()
        }
    }
}
like image 86
Tung Fam Avatar answered Nov 16 '22 00:11

Tung Fam


Swift 3 solution in my case:

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.titleView = mySearchController.searchBar
    mySearchController.searchResultsUpdater = self
    mySearchController.delegate = self

}

override func viewDidAppear(_ animated: Bool) {
    DispatchQueue.main.async {
        self.mySearchController.isActive = true
    }
}

func presentSearchController(_ searchController: UISearchController) {
    mySearchController.searchBar.becomeFirstResponder()
}
like image 23
Vitya Shurapov Avatar answered Nov 16 '22 00:11

Vitya Shurapov