3
votes

So I have an UIImageView inside of a UIScrollView, I need to capture both: - single tap gesture - double tap gesture for the UIImageView

The double tap gesture is supposed to be sent to the UIScrollView as an action of zooming The single tap gesture is captured by a UITapGestureRecognizer that I created myself. The double tap gesture has higher priority than the single tap (when there is a double tap, zoom in the scrollview, else perform the single tap)

So far if I add the single tap gesture recognizer to the scrollview, the single tap is immediately recognized and no double tap can be recognized.

If I add the single tap gesture recognizer to the imageview, it never receives any action, but double tap works

Any suggestion is appreciated, thanks..

3

3 Answers

6
votes

try this code,

Objective - C

 UITapGestureRecognizer *singletap = [[UITapGestureRecognizer alloc]
                                                     initWithTarget:self
                                                     action:@selector(singleTap:)];
    singletap.numberOfTapsRequired = 1;
    singletap.numberOfTouchesRequired = 1;

[scrollView addGestureRecognizer:singletap];


UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc]
                                                 initWithTarget:self
                                                 action:@selector(doubleTap:)];
doubleTap.numberOfTapsRequired =2 ;
doubleTap.numberOfTouchesRequired = 1;

[scrollView addGestureRecognizer:doubleTap];



[singleTap requireGestureRecognizerToFail:doubleTap];

Swift 3.0

var singletap = UITapGestureRecognizer(target: self, action: #selector(self.singleTap))
singletap.numberOfTapsRequired = 1
singletap.numberOfTouchesRequired = 1
scrollView.addGestureRecognizer(singletap)
var doubleTap = UITapGestureRecognizer(target: self, action: #selector(self.doubleTap))
doubleTap.numberOfTapsRequired = 2
doubleTap.numberOfTouchesRequired = 1
scrollView.addGestureRecognizer(doubleTap)
singleTap.require(toFail: doubleTap)
2
votes

The top answer actually has the last line inverted. The correct code should be:

[singleTap requireGestureRecognizerToFail:doubleTap];
1
votes
UITapGestureRecognizer *tapRecognizerForSingleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction:)];
[tapRecognizerForSingleTap setNumberOfTapsRequired:1];

UITapGestureRecognizer *tapRecognizerForDoubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapAction:)];
[tapRecognizerForDoubleTap setNumberOfTapsRequired:2];

Both are added in a same image view and to achieve what you want just add the below line.

[tapRecognizerForSingleTap requireGestureRecognizerToFail:tapRecognizerForDoubleTap];

By the above line you are asking for single tap will be only recognise if it's not double tap.