As we know, we use the below code can endEditing the searchBar's firstResponder, but if there is a scrollView or tableView, the effect is different.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)

    self.view.endEditing(true)
}

I add the tapGesture to tableView, so I can endEditing the searchBar's firstResponder.

But after add the tapGesture to my tableView, the tableView's tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) function will not work any more.

How can I solve the issue?


Addition

My useful code is below:

let tap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapTableView))
self.tableView.addGestureRecognizer(tap)


func tapTableView() {

    self.searchBar.endEditing(true)
}
2

There are 2 answers

2
Gurinder Batth On

add the tapGesture on the view not on tableView

let tap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapTableView))
self.view.addGestureRecognizer(tap)
1
Sean Lintern On

Instead on your table view add

    tableView.keyboardDismissMode = .onDrag

You can change .onDrag to .interactive too. Remove the Touches began.

Edit: From apple docs

case none
    The keyboard does not get dismissed with a drag.
case onDrag
    The keyboard is dismissed when a drag begins.
case interactive
    The keyboard follows the dragging touch offscreen, and can be pulled upward again to cancel the dismiss.