为什么"shouldReceiveTouch"返回"NO","PanGesture"仍然有效?



例如title,我有一个superView a和一个childView B。a有一个panGestureRecognizer。当我滑动B时,它会触发A的panGestureRecognizer。所以我在A的shouldReceiveTouch中返回No,但PanGesture Recognizer仍然有效,这让我很困惑。

我使用了以下内容,它似乎按预期工作:

class ViewController: UIViewController {
private lazy var topView: UIView = {
let view = UIView(frame: .init(x: 100.0, y: 200.0, width: 200.0, height: 200.0))
view.backgroundColor = UIColor.green
return view
}()

override func viewDidLoad() {
super.viewDidLoad()

let bottomView = self.view
bottomView?.backgroundColor = UIColor.red
bottomView?.addSubview(topView)
bottomView?.addGestureRecognizer({
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(onPan))
panGesture.delegate = self
return panGesture
}())
}

private var stateString: String = "" {
didSet {
if stateString != oldValue {
print("State changed to (stateString)")
}
}
}

@objc private func onPan(_ sender: UIGestureRecognizer) {
switch sender.state {
case .began: stateString = "begin"
case .changed: stateString = "changed"
case .ended: stateString = "ended"
case .cancelled: stateString = "canceled"
default: stateString = "some thing else"
}
}
}

extension ViewController: UIGestureRecognizerDelegate {

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return topView.bounds.contains(touch.location(in: topView)) == false
}

}

手势只有在从绿色视图开始时才有效。一旦手势开始,事件将正常触发,包括在绿色视图中。

最新更新