Search code examples
iosswiftuiscrollviewuisearchcontroller

Keyboard dismiss for search controller in navigation item on tap anywhere


I've got UITableViewController with UISearchController in the navigation's item title view. I want to make keyboard dismiss on tap anywhere in table view. How to make it?

This is my code so far:

extension UIViewController {

    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
    func dismissKeyboard() {
        view.endEditing(true)
    }
}

class TableViewController: UITableViewController, UISearchResultsUpdating {

    override func viewDidLoad() {
        super.viewDidLoad()
        hideKeyboardWhenTappedAround()

        let searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = self

        navigationItem.titleView = searchController.searchBar
    }

    func updateSearchResults(for searchController: UISearchController) {
        //
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 40
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath)
        cell.textLabel?.text = "test1"
        return cell
    }
}

Solution

  • Your searchController isn't in ViewController view hierarchy, it's in NavigationController view hierarchy there is why your code not working.

    If you change your code to this`

    func dismissKeyboard() {
        navigationController?.view.endEditing(true)
    }
    

    it will work.