UIControl 子类正在接收“touchesCancelled”而不是“touchesEnded”

Aug*_*rmo 2 uicontrol ios swift

在我的项目中,我有一个主视图,在其中添加了一个UITapGestureRecognizer,在这个主视图中,我有一个自定义的子视图UIControl,我将其称为UICustomButton

重写UICustomButton以下方法UIControl

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        pressAnimation()
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        releaseAnimation()
        listener?.onClick(sender: self)
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesCancelled(touches, with: event)
        releaseAnimation()
    }
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,所有“点击触摸”都会触发以下回调:

  • touchesBegan
  • touchesCancelled

回调touchesEnded没有被调用,它有点被忽略,我不知道为什么。

我怎样才能让touchesEnded被调用而不是touchesCancelled通过触摸操作?


一些事实:

  • 如果我从父视图中删除UITapGestureRecognizer,一切正常;
  • 即使不调用 thesupers并重写所有touches方法, thetouchesCancelled也会被调用 =/;
  • 如果我做了“长触摸”或做了“大移动手势”,touchesEnded则称为:o。

Pet*_*ris 7

对于附加了手势识别器的视图来说,这是正确的行为。

UIGestureRecognizer文档说“如果手势识别器识别出其手势,则视图的剩余触摸将被取消”:

https://developer.apple.com/documentation/uikit/uigesturerecognizer

该属性cancelsTouchesInView(默认为true)确定识别手势时是否取消触摸:

https://developer.apple.com/documentation/uikit/uigesturerecognizer/1624218-cancelstouchesinview

由于长按和滑动不会点击识别器识别,因此不会干扰它们。它在识别出轻敲时进行干预。

如果将识别器的cancelsTouchesInView属性设置为false,则不应取消触摸,并且touchesEnded(_:with:)将照常调用该方法。

您可以在代码或 Interface Builder 中设置该属性(如果您通过将手势识别器拖到故事板中来添加)。