我有一个UIPanGestureRecognizer
用于跟踪UIImageView
用户手指下方的对象 ( )。我只关心 X 轴上的运动,如果触摸偏离 Y 轴上对象框架的上方或下方,我想结束触摸。
我拥有确定触摸是否在对象的 Y 范围内所需的一切,但我不知道如何取消触摸事件。翻转识别器的cancelsTouchesInView
属性似乎并没有达到我想要的效果。
谢谢!
我有一个UIPanGestureRecognizer
用于跟踪UIImageView
用户手指下方的对象 ( )。我只关心 X 轴上的运动,如果触摸偏离 Y 轴上对象框架的上方或下方,我想结束触摸。
我拥有确定触摸是否在对象的 Y 范围内所需的一切,但我不知道如何取消触摸事件。翻转识别器的cancelsTouchesInView
属性似乎并没有达到我想要的效果。
谢谢!
这个小技巧对我有用。
@implementation UIGestureRecognizer (Cancel)
- (void)cancel {
self.enabled = NO;
self.enabled = YES;
}
@end
从UIGestureRecognizer @enabled
文档中:
禁用手势识别器,使其不接收触摸。默认值为是。如果在手势识别器当前正在识别手势时将此属性更改为 NO,则手势识别器将转换为取消状态。
@matej 在 Swift 中的回答。
extension UIGestureRecognizer {
func cancel() {
isEnabled = false
isEnabled = true
}
}
对象-C:
recognizer.enabled = NO;
recognizer.enabled = YES;
斯威夫特 3:
recognizer.isEnabled = false
recognizer.isEnabled = true
苹果文档中的这个怎么样:
@property(nonatomic, getter=isEnabled) BOOL enabled
禁用手势识别器,使其不接收触摸。默认值为是。如果在手势识别器当前正在识别手势时将此属性更改为 NO,则手势识别器将转换为取消状态。
根据文档,您可以对手势识别器进行子类化:
在 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
只需recognizer.state
在您的handlePan(_ recognizer: UIPanGestureRecognizer)
方法中设置为.ended
或.cancelled
You have a couple ways of handling this:
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.
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.