Method to make UIGestureRecognizer fail after being recognized?
I have a question that might seem basic but can't figure it out.
Basic question is: how do I programmatically put a gesturerecognizer into fail state from handler, while it's in UIGestureRecognizerStateBegan or UIGestureRecognizerStateChanged?
More detailed explanation: I have a long press gesture recognizer for UIView inside a UIScrollView. I have made
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
because else I can't get scroll view to scroll once user puts their finger down at the view. It's basic touch like safari, where you hold finger down on a link, which highl开发者_JS百科ights the link, but scroll up or down - then link is unhighlighted and scrollview moves.
I can get this mostly working right now since both gestures are being recognized, but it would be better if I can detect movement in longpress gesturerecognizer's StateChanged, and if it's more than 20 pixels or so, just programmatically make longpress fail.
Is this possible to do? Or am I digging at a wrong spot?
Another question that I found right after I posted the question..
Here's what I do in the gesture recognizer handler now:
else if (sender.state == UIGestureRecognizerStateChanged) {
CGPoint newTouchPoint = [sender locationInView:[self superview]];
CGFloat dx = newTouchPoint.x - initTouchPoint.x;
CGFloat dy = newTouchPoint.y - initTouchPoint.y;
if (sqrt(dx*dx + dy*dy) > 25.0) {
sender.enabled = NO;
sender.enabled = YES;
}
}
So if finger moves more than 25 pixels in any direction, setting enabled property to NO will make the recognizer fail. So this will accomplish what I want!
If it is a UILongPressGestureRecognizer
, just set its allowableMovement
property.
UILongPressGestureRecognizer* recognizer = [your recognizer];
recognizer.allowableMovement = 25.0f;
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
精彩评论