区分单击和双击手势

公司项目里用URBMediaFocusViewController来

animates thumbnail previews of your media to their full size versions with physics similar to Tweetbot 3.

结果当单击图片后发现图片的弹出速度比较慢。后来发现是因为同时在图片上添加了单击和双击俩种手势。为了区分单击和双击使用了[singleTapGestureRecognizer requireGestureRecognizerToFail: doubleTapGestureRecognizer];方法,但是这个区分单击和双击的时间有点长,因而导致了图片弹出速度有点慢。根据How to recognize oneTap/doubleTap at moment? 这个答案改写出下面的代码。

#import "HBJFShortTapGestureRecognizer.h"

#define DELAY_SECONDS 0.28

@implementation HBJFShortTapGestureRecognizer

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(DELAY_SECONDS * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if (self.state != UIGestureRecognizerStateRecognized) {
            self.state = UIGestureRecognizerStateFailed;
        }

    });

}

@end

注意:在头文件里要添加#import

在看这个代码里的时候突然对UITapGestureRecognizerUIGestureRecognizerState感到很迷惑。

typedef enum {
   UIGestureRecognizerStatePossible,
   
   UIGestureRecognizerStateBegan,
   UIGestureRecognizerStateChanged,
   UIGestureRecognizerStateEnded,
   UIGestureRecognizerStateCancelled,
   
   UIGestureRecognizerStateFailed,
   
   UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded
} UIGestureRecognizerState;

上面是所有的UIGestureRecognizerState,而且里面UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded很是让我不解。在detecting finger up/down UITapGestureRecognizer上面查到

UITapGestureRecognizer is a discrete gesture recognizer, and therefore never transitions to the began or changed states. From the UIGestureRecognizer Class Reference:

Discrete gestures transition from Possible to either Recognized (UIGestureRecognizerStateRecognized) or Failed (UIGestureRecognizerStateFailed), depending on whether they successfully interpret the gesture or not. If the gesture recognizer transitions to Recognized, it sends its action message to its target.

从这里可以知道,UITapGestureRecognizerdiscrete手势,不是continuous手势,因而UITapGestureRecognizer只有3种UIGestureRecognizerStateUIGestureRecognizerStatePossible UIGestureRecognizerStateRecognizedUIGestureRecognizerStateFailed。而continuous手势的UIGestureRecognizerStateUIGestureRecognizerStatePossible UIGestureRecognizerStateBegan UIGestureRecognizerStateChanged UIGestureRecognizerStateEndedUIGestureRecognizerStateCancelled

到此,所有的疑惑都解决了。

你可能感兴趣的:(区分单击和双击手势)