Activate UISearchBar when the controller is loaded

2019-06-01 08:47发布

问题:

I have the following SearchController:

class SearchController: UITableViewController, UISearchResultsUpdating

The implementation works well, but I have to tap on the search bar to start searching every time I load the controller. What I'd like is to activate the search bar once SearchController is loaded. I have tried with:

override func viewDidLoad() {
    super.viewDidLoad()

    ...
    ...

    self.resultSearchController.searchBar.becomeFirstResponder()
}

I also tried with:

override func viewDidAppear(animated: Bool) {
    self.resultSearchController.searchBar.becomeFirstResponder()
}

But the search bar remains deactivated and the keyboard won't show up. What am I missing? Thanks!

回答1:

This works (not sure why it's not working for you):

class ViewController: UIViewController {

    let mySearchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.titleView = mySearchController.searchBar
        mySearchController.hidesNavigationBarDuringPresentation = false
        mySearchController.searchBar.becomeFirstResponder()
    }
}