I have a UIPanGestureRecognizer
I am using to track an object (UIImageView
) below a user\'s finger. I only care about motion on the X axis, and if
This little trick works for me.
@implementation UIGestureRecognizer (Cancel)
- (void)cancel {
self.enabled = NO;
self.enabled = YES;
}
@end
From the UIGestureRecognizer @enabled
documentation:
Disables a gesture recognizers so it does not receive touches. The default value is YES. If you change this property to NO while a gesture recognizer is currently recognizing a gesture, the gesture recognizer transitions to a cancelled state.
According to the documentation you can subclass you gesture recogniser:
In YourPanGestureRecognizer.m:
#import "YourPanGestureRecognizer.h"
@implementation YourPanGestureRecognizer
- (void) cancelGesture {
self.state=UIGestureRecognizerStateCancelled;
}
@end
In YourPanGestureRecognizer.h:
#import <UIKit/UIKit.h>
#import <UIKit/UIGestureRecognizerSubclass.h>
@interface NPPanGestureRecognizer: UIPanGestureRecognizer
- (void) cancelGesture;
@end
Now you can call if from anywhere
YourPanGestureRecognizer *panRecognizer = [[YourPanGestureRecognizer alloc] initWithTarget:self action:@selector(panMoved:)];
[self.view addGestureRecognizer:panRecognizer];
[...]
-(void) panMoved:(YourPanGestureRecognizer*)sender {
[sender cancelGesture]; // This will be called twice
}
Ref: https://developer.apple.com/documentation/uikit/uigesturerecognizer?language=objc
Obj-C:
recognizer.enabled = NO;
recognizer.enabled = YES;
Swift 3:
recognizer.isEnabled = false
recognizer.isEnabled = true
@matej's answer in Swift.
extension UIGestureRecognizer {
func cancel() {
isEnabled = false
isEnabled = true
}
}
How about this from the apple docs:
@property(nonatomic, getter=isEnabled) BOOL enabled
Disables a gesture recognizers so it does not receive touches. The default value is YES. If you change this property to NO while a gesture recognizer is currently recognizing a gesture, the gesture recognizer transitions to a cancelled state.
Just set recognizer.state
in your handlePan(_ recognizer: UIPanGestureRecognizer)
method to .ended
or .cancelled