Swift 5とiOS 12では、UIGestureRecognizerDelegate
というメソッドがありgestureRecognizer(_:shouldReceive:)
ます。gestureRecognizer(_:shouldReceive:)
次の宣言があります:
ジェスチャレコグナイザがタッチを表すオブジェクトを受け取るかどうかをデリゲートに尋ねます。
optional func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool
以下の完全なコードは、の可能な実装を示していますgestureRecognizer(_:shouldReceive:)
。このコードでは、ViewController
のビュー(を含むimageView
)のサブビューをタップしてもprintHello(_:)
メソッドはトリガーされません。
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")
}
}
の代替実装はgestureRecognizer(_:shouldReceive:)
次のとおりです。
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return gestureRecognizer.view === touch.view
}
ただし、この代替コードtouch.view
はがのサブビューかどうかをチェックしないことに注意してくださいgestureRecognizer.view
。