0

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)
}

}

Miquel Molina
  • 23
  • 2
  • 8

2 Answers2

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.

N Brown
  • 507
  • 3
  • 9
  • As I implement the gestureRecognizer (_: shouldReceive :) method to cancel the touches if the TableView is touched, I can not find the way – Miquel Molina Mar 11 '18 at 19:03
  • Are you having issues with setting up the delegate or determining if the touch is in the tableview? I found the answer to the second on what looks like an almost identical question to yours here: https://stackoverflow.com/questions/8192480/uitapgesturerecognizer-breaks-uitableview-didselectrowatindexpath. – N Brown Mar 11 '18 at 19:09
-1

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
    }
}
Eray Alparslan
  • 806
  • 7
  • 12