为什么 "shouldReceiveTouch" returns "NO", "PanGesture" 仍然有效?
why the "shouldReceiveTouch" returns "NO", the "PanGesture" still works?
如题,我有一个superView A和一个childView B,A有一个panGestureRecognizer。当我滑动B时,它会触发A的panGestureRecognizer。所以我return在A的shouldReceiveTouch中没有,但是panGestureRecognizer仍然有效,这让我很困惑。
我使用了以下内容,它似乎按预期工作:
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
}
}
手势仅在从绿色视图开始时有效。
一旦手势开始,事件将正常触发,包括在绿色视图中。
如题,我有一个superView A和一个childView B,A有一个panGestureRecognizer。当我滑动B时,它会触发A的panGestureRecognizer。所以我return在A的shouldReceiveTouch中没有,但是panGestureRecognizer仍然有效,这让我很困惑。
我使用了以下内容,它似乎按预期工作:
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
}
}
手势仅在从绿色视图开始时有效。 一旦手势开始,事件将正常触发,包括在绿色视图中。