Con Swift 5 y iOS 12, UIGestureRecognizerDelegate
tiene un método llamado gestureRecognizer(_:shouldReceive:)
. gestureRecognizer(_:shouldReceive:)
tiene la siguiente declaración:
Pregunte al delegado si un reconocedor de gestos debería recibir un objeto que represente un toque.
optional func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool
El código completo a continuación muestra una posible implementación para gestureRecognizer(_:shouldReceive:)
. Con este código, un toque en una subvista de la ViewController
vista de '(incluida imageView
) no activará el printHello(_:)
método.
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)
// ⚠️ Enable user interaction for imageView so that it can participate to touch events.
// Otherwise, taps on imageView will be forwarded to its superview and managed by it.
imageView.isUserInteractionEnabled = true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
// Prevent subviews of a specific view to send touch events to the view's gesture recognizers.
if let touchedView = touch.view, let gestureView = gestureRecognizer.view, touchedView.isDescendant(of: gestureView), touchedView !== gestureView {
return false
}
return true
}
@objc func printHello(_ sender: UITapGestureRecognizer) {
print("Hello")
}
}
Una implementación alternativa de gestureRecognizer(_:shouldReceive:)
puede ser:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return gestureRecognizer.view === touch.view
}
Sin embargo, touch.view
tenga en cuenta que este código alternativo no comprueba si es una subvista de gestureRecognizer.view
.