比如title,我有一個superView A和一個childView B。A有一個panGestureRecognizer。當我滑動 B 時,它會觸發 A 的 panGestureRecognizer。所以我在 A 的 shouldReceiveTouch 中回傳 No,但是 panGestureRecognizer 仍然有效,這讓我感到困惑。
uj5u.com熱心網友回復:
我使用了以下內容,它似乎按預期作業:
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
}
}
手勢僅在從綠色視圖開始時才有效。一旦手勢開始,事件將正常觸發,包括在綠色視圖中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/426049.html
