1

I want to add multiple UITapGestureRecognizer on UIScrollView but it recognise only one gesture.
I want to add first gesture for touch begin and second one for touch end event.

Following is my code:-

self.tapStartGesture = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapGesture:)];
self.tapStartGesture.numberOfTapsRequired = 1;
self.tapStartGesture.numberOfTouchesRequired = 1;
[self.tapStartGesture setState:UIGestureRecognizerStateBegan];
[self.scrollView addGestureRecognizer:self.tapStartGesture];

self.tapEndGesture = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapGesture:)];
self.tapEndGesture.numberOfTapsRequired = 1;
self.tapEndGesture.numberOfTouchesRequired = 1;
[self.scrollView addGestureRecognizer:self.tapEndGesture];

- (void)tapGesture:(UITapGestureRecognizer *)sender {
    if(sender==self.tapStartGesture) {
        NSLog(@"tapStartGesture");
    } else if(sender==self.tapEndGesture) {
        NSLog(@"tapEndGesture");
    }
}
Bhavesh Nayi
  • 705
  • 4
  • 15
Bhaumik Surani
  • 1,730
  • 3
  • 19
  • 40

2 Answers2

2

A tap gesture only has one state - "ended". You can't detect when a tap starts using a tap gesture. As you've seen, attempting to use two tap gestures doesn't accomplish what you want.

You need to implement the UIResponder methods touchesBegan and touchesEnded.

You may also want to see UITapGestureRecognizer - make it work on touch down, not touch up? .

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Every time recognizing *tapEndGesture*. tapStartGesture is not call – Bhaumik Surani Apr 29 '19 at 06:18
  • Oh right. A tap gesture only has the one state. It''s only a tap gesture if, at the end, it has been recognized as an actual tap. You can't get a "began" state for a tap gesture. If you want to know when a user touches the screen and again when they stop touching the screen, look into overriding the `touchesBegan` and `touchesEnded` methods from `UIResponder`. – rmaddy Apr 29 '19 at 06:22
0

Issue solved by implement custom gesture.

File:-MyGesture.h

#import <UIKit/UIKit.h>
@interface MyGesture : UIGestureRecognizer
@end

File:-MyGesture.m

#import "MyGesture.h"
@implementation MyGesture    
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (self.state == UIGestureRecognizerStatePossible) {;
        self.state = UIGestureRecognizerStateBegan;
    }
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    self.state = UIGestureRecognizerStateEnded;
}    
@end

How to Use:-

MyGesture *gesture = [[MyGesture alloc] initWithTarget:self action:@selector(myGesture:)];
[self.scrollView addGestureRecognizer:gesture];

- (void)myGesture:(MyGesture *)sender {
    if (sender.state == UIGestureRecognizerStateBegan) {
        NSLog(@"tapStartGesture");
    } else if (sender.state == UIGestureRecognizerStateEnded) {
        NSLog(@"tapEndGesture");
    }
}
Bhaumik Surani
  • 1,730
  • 3
  • 19
  • 40