70

我有一个UIPanGestureRecognizer用于跟踪UIImageView用户手指下方的对象 ( )。我只关心 X 轴上的运动,如果触摸偏离 Y 轴上对象框架的上方或下方,我想结束触摸。

我拥有确定触摸是否在对象的 Y 范围内所需的一切,但我不知道如何取消触摸事件。翻转识别器的cancelsTouchesInView属性似乎并没有达到我想要的效果。

谢谢!

4

7 回答 7

161

这个小技巧对我有用。

@implementation UIGestureRecognizer (Cancel)

- (void)cancel {
    self.enabled = NO;
    self.enabled = YES;
}

@end

UIGestureRecognizer @enabled文档中:

禁用手势识别器,使其不接收触摸。默认值为是。如果在手势识别器当前正在识别手势时将此属性更改为 NO,则手势识别器将转换为取消状态。

于 2010-11-12T17:38:41.700 回答
13

@matej 在 Swift 中的回答。

extension UIGestureRecognizer {
  func cancel() {
    isEnabled = false
    isEnabled = true
  }
}
于 2016-04-08T07:15:59.373 回答
10

对象-C:

recognizer.enabled = NO;
recognizer.enabled = YES;

斯威夫特 3:

recognizer.isEnabled = false
recognizer.isEnabled = true
于 2016-04-20T18:28:12.493 回答
4

苹果文档中的这个怎么样:

@property(nonatomic, getter=isEnabled) BOOL enabled

禁用手势识别器,使其不接收触摸。默认值为是。如果在手势识别器当前正在识别手势时将此属性更改为 NO,则手势识别器将转换为取消状态。

于 2012-05-15T12:56:53.607 回答
3

根据文档,您可以对手势识别器进行子类化:

在 YourPanGestureRecognizer.m 中:

#import "YourPanGestureRecognizer.h"

@implementation YourPanGestureRecognizer

- (void) cancelGesture {
    self.state=UIGestureRecognizerStateCancelled;
}

@end

在 YourPanGestureRecognizer.h 中:

#import <UIKit/UIKit.h>
#import <UIKit/UIGestureRecognizerSubclass.h>

@interface NPPanGestureRecognizer: UIPanGestureRecognizer

- (void) cancelGesture;

@end

现在您可以从任何地方拨打电话

YourPanGestureRecognizer *panRecognizer = [[YourPanGestureRecognizer alloc] initWithTarget:self action:@selector(panMoved:)];
[self.view addGestureRecognizer:panRecognizer];
[...]
-(void) panMoved:(YourPanGestureRecognizer*)sender {
    [sender cancelGesture]; // This will be called twice
}

参考:https ://developer.apple.com/documentation/uikit/uigesturerecognizer?language=objc

于 2017-10-12T17:25:19.927 回答
2

只需recognizer.state在您的handlePan(_ recognizer: UIPanGestureRecognizer)方法中设置为.ended.cancelled

于 2020-01-09T08:08:56.217 回答
0

You have a couple ways of handling this:

  1. If you were writing a custom pan gesture recognizer subclass, you could easily do this by calling -ignoreTouch:withEvent: from inside the recognizer when you notice it straying from the area you care about.

  2. Since you're using the standard Pan recognizer, and the touch starts off OK (so you don't want to prevent it with the delegate functions), you really can only make your distinction when you receive the recognizer's target actions. Check the Y value of the translationInView: or locationInView: return values, and clamp it appropriately.

于 2011-08-15T14:38:29.317 回答