In Swift 5 and iOS 12, UIGestureRecognizerDelegate has a method called gestureRecognizer(_:shouldReceive:) . gestureRecognizer(_:shouldReceive:) has the following declaration:
Ask the delegate if the gesture recognizer should receive an object that represents the touch.
optional func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool
The full code below shows a possible implementation for gestureRecognizer(_:shouldReceive:) . With this code, clicking on the ViewController the ViewController (including imageView ) will not call the printHello(_:) method.
import UIKit class ViewController: UIViewController, UIGestureRecognizerDelegate { override func viewDidLoad() { super.viewDidLoad() let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(printHello)) tapGestureRecognizer.delegate = self view.addGestureRecognizer(tapGestureRecognizer) let imageView = UIImageView(image: UIImage(named: "icon")!) imageView.frame = CGRect(x: 50, y: 50, width: 100, height: 100) view.addSubview(imageView)
An alternative implementation of gestureRecognizer(_:shouldReceive:) could be:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return gestureRecognizer.view === touch.view }
However, note that this alternative code does not check if touch.view gestureRecognizer.view .
Imanou Petit Jul 31 '18 at 20:54 2018-07-31 20:54
source share