QuantumHoneybees QuantumHoneybees - 5 months ago 82
Swift Question

Dismiss keyboard when uitableview cell is selected and using UISearchController

So I have an app that is basically a movie search app displayed using a UITableViewController and a UISearchController.

I have a cell that when tapped, loads more results. But when I tap it, I also want the keyboard to go away. So in the

tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
method, I assume I have to call
resignFirstResponder()
. The problem is that it doesn't work. I've tried everything but nothing makes the keyboard disappear. I think it's because the keyboard is part of the UISearchBar, and I should call
searchBar.resignFirstResponder()
. The problem is that I can't access the searchBar from my
UITableViewController
class.

Here is what I have, none of this works:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//Remove Keyboard
self.resignFirstResponder()
self.view.resignFirstResponder()
self.view.endEditing(true)
self.tableView.endEditing(true)
self.navigationController?.view.endEditing(true)
self.navigationController?.resignFirstResponder()

//Do a bunch of other stuff..
}

Answer

If you know that the searchBar is the first responder then either:

  1. Pass a reference to the searchBar to the UITableViewController
  2. Use KVC: Post a notification that you're loading more results and keyboard should be hidden, and in your UISeachController listen for that notification.