'Cancel gesturerecognizer when touching UITableView

I have a view with 2 tableview and several textfield, I have implemented an extension to hide the keyboard:

The keyboard hides when I touch the screen but I would like to disable UITapGestureRecognizer when I touch the TableView, otherwise I can not interact with the cells.

extension UIViewController {

func OcultarTecladoTocarPantalla() {
    let tap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.OcultarTeclado))
    view.addGestureRecognizer(tap)
}
@objc func OcultarTeclado() {
    view.endEditing(true)
}

}



Solution 1:[1]

EDIT: I see that you are extending UIViewController (which may not be advisable because it applies to all instances and subclasses of UIViewController), but you should still be able to set up the delegate. Make the following changes (code is pulled from this answer).

Extend UIGestureRecognizerDelegate by writing extension UIViewController: UIGestureRecognizerDelegate {

Set the delegate when you add the gesture recognizer: tap.delegate = self

Implement the following delegate method. It will need to be modified slightly to handle two tableviews.

// UIGestureRecognizerDelegate method
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    if touch.view?.isDescendantOfView(self.tableView) == true {
        return false
    }
    return true
}

Previous answer:

If the cancelsTouchesInView property of UIGestureRecognizer is false the view underneath it will receive touches in addition to the gesture recognizer.

If you do want to effectively disable the gesture for that case, implement the delegate method gestureRecognizer(_:shouldReceive:) and return false if the touch is in the tableview.

See https://developer.apple.com/documentation/uikit/uigesturerecognizer and https://developer.apple.com/documentation/uikit/uigesturerecognizerdelegate/1624214-gesturerecognizer.

Solution 2:[2]

For Swift 5: (Don't forget to set delegate of your tap gesture instance)

extension MyViewController: UIGestureRecognizerDelegate{
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if touch.view?.isDescendant(of: self.mTableView) == true {
            return false
        }
        return true
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2