【问题标题】:UIView touchesBegan won't fire when UILongPressGestureRecognizer minimumPressDuration zero当 UILongPressGestureRecognizer minimumPressDuration 为零时,UIView touchesBegan 不会触发
【发布时间】:2021-08-17 18:20:20
【问题描述】:

如果手势 minimumPressDuration 设置为“.zero”,MyView 和 ViewController 的 touchesBegan 将不会触发,但每当我将其设置为“.leastNormalMagnitude”时它就会触发。代码如下:

class ViewController: UIViewController {

    let mySuperView: UIView = {
        let v = UIView()
        v.backgroundColor = .blue
        v.frame = CGRect(origin: CGPoint(x: 100, y: 100), size: CGSize(width: 500, height: 500))
        return v
    }()
    
    let mySubview: MyView = {
        let v = MyView()
        v.backgroundColor = .orange
        v.frame = CGRect(origin: CGPoint(x: 100, y: 100), size: CGSize(width: 250, height: 250))
        return v
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.addSubview(mySuperView)
        
        mySuperView.addSubview(mySubview)
        
        let gesture = UILongPressGestureRecognizer(target: self, action: #selector(tapped(_:)))        

        gesture.minimumPressDuration = .zero // when it's set to ".leastNormalMagnitude",
                                             // MyView's and VC's touchesBegan fires.

        mySuperView.addGestureRecognizer(gesture)
    }

    @objc func tapped(_ gesture: UITapGestureRecognizer) {
        print("long pressed.")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("touchesBegan in vc") // -> Won't get called.
        super.touchesBegan(touches, with: event)
    }
    
}

class MyView: UIView {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("touchesBegan in MyViewClass") // -> Won't get called.
        super.touchesBegan(touches, with: event)
    }
}

我想我可以将它与“.leastNormalMagnitude”一起使用,但我仍然想知道为什么会这样?

【问题讨论】:

  • 按零时间是什么意思?我想这意味着你没有按下它。
  • @matt 仅用于激活时间。我希望长按手势立即触发。
  • 但这不会是一个长按

标签: ios swift touchesbegan


【解决方案1】:

尽管在必须使用UITapGestureRecognizer 的情况下误用了UILongPressGestureRecognizer,但我将重点回答“为什么”部分。

当您设置gesture.minimumPressDuration = .zero 时,长按手势会立即被识别。

默认情况下,手势识别器倾向于延迟视图中的触摸,并在识别手势时取消它们。

为了覆盖这个行为,设置

gesture.cancelsTouchesInView = false // to recieve touchesBegan callback even if gesture is recognized
gesture.delaysTouchesBegan = false // to not delay touchesBegan callback
gesture.delaysTouchesEnded = false // to not delay touchesEnded callback

【讨论】:

  • 感谢您的回答!你认为 UITapGestureRecognizer 应该与 touchesBegan 方法中的即时点击修改一起使用吗?我正在尝试在触摸按下时立即获得即时触摸反馈。
  • 您应该使用手势识别器或touchesBegan 回调,而不是两者。如果您只需要识别“内部触地”,那么touchesBegan 回调可能就足够了。如果您没有任何手势识别器可能会阻止它被立即分派,那么该回调将立即被调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多