2011-09-07 128 views
5

我有一個問題,可能看起來很基本,但無法弄清楚。使UIGestureRecognizer識別失敗的方法?

基本問題是:我如何以編程方式將gesturerecognizer從處理程序置於失敗狀態,而它處於UIGestureRecognizerStateBegan或UIGestureRecognizerStateChanged中?

更詳細的解釋:我有UIScrollView內的UIView長按手勢識別器。我製作了

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { 
    return YES; 
} 

因爲否則我無法在用戶將手指放在視圖中時滾動視圖來滾動。這是基本的觸摸,如safari,您可以將手指放在鏈接上,突出顯示鏈接,但向上或向下滾動 - 然後鏈接不顯示,滾動視圖移動。

由於兩個手勢都被識別,所以我現在可以正常工作,但是如果我可以檢測到longpress gesturerecognizer的StateChanged中的移動,並且它的像素超過20像素,那麼只是通過編程使longpress失敗。

這可能嗎?或者我挖了一個錯誤的地方?

回答

4

另一個問題,我找到了正確的我張貼的問題後..

下面是我在手勢識別處理現在要做的:

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; 
    } 
} 

因此,如果手指在任何方向移動超過25個像素,將啓用屬性設置爲NO將使識別器失敗。所以這將完成我想要的!

4

如果是UILongPressGestureRecognizer,只需設置它的allowableMovement屬性。

UILongPressGestureRecognizer* recognizer = [your recognizer]; 
recognizer.allowableMovement = 25.0f; 
1

根據該文件,那麼可以繼承你的手勢識別器:

在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