13

Say I am currently tracking a drag gesture. In my event handler I use a threshold to determine when the drag results in an action. When the threshold is crossed, I want to indicate that the drag gesture has completed.

The only thing I can find in the docs is this line here:

If you change this property to NO while a gesture recognizer is currently recognizing a gesture, the gesture recognizer transitions to a cancelled state.

So:

if (translation.y > 100) {
    // do action
    [self doAction];

    //end recognizer
    sender.enabled = NO;
    sender.enabled = YES;
}

This works but it looks like there might be a neater way.

Does anyone know of another way to indicate that a gesture has ended programmatically? I would expect something like a method -end: that generates a final event with state UIGestureRecognizerStateEnded.

4

2 回答 2

15

您是否定义了自定义 UIGestureRecognizer?如果您要识别的手势与 Apple 定义的标准手势不同,因为它具有不同的阈值,或者与常规 UIPanGestureRecognizer 不同,那么创建自己的 UIGestureRecognizer 可能是有意义的。(见子类注释

如果你有 UIGestureRecognizer 的子类,你可以像这样简单地设置状态:

  self.state = UIGestureRecognizerStateEnded;

您可能希望在 touchesMoved:withEvent: 方法中执行此操作。另请注意:

“UIGestureRecognizer 的子类必须导入 UIGestureRecognizerSubclass.h。此头文件包含状态的重新声明,使其可读写。”

另一方面,如果只实现一个 UIGestureRecognizerDelegate,则状态为只读,无法直接设置。在这种情况下,您的禁用/启用方法可能是您能做的最好的。

于 2012-09-05T20:16:29.503 回答
5

使用您显示的代码,您需要具有在取消手势识别器时启动动画的逻辑,我会说这不好,因为还有其他方法可以取消此手势识别器而您不想完成动画.

考虑到您有一个启动动画的方法,您只需要在超过阈值并且手势正常结束时调用此方法。那么两个不同的场合。您提供的代码如下所示:

if (translation.y > 100) {
    // do action
    [self finishFlip];
    sender.enabled = NO;
    sender.enabled = YES;
}

如果用户一直拖动手指,如果这样做会阻止任何后续操作,那么在此处取消手势也可能很有用。

如果您将有一个团队为此进行开发并且您需要发生特定事件,您应该将手势识别器子类化为非建议的子类。

于 2012-09-06T06:56:55.690 回答