多个 UITapGestureRecognizer 不适用于 UIScrollView

Multiple UITapGestureRecognizer not working on UIScrollView

我想在 UIScrollView 上添加多个 UITapGestureRecognizer,但它只能识别一个手势。
我想为触摸开始添加第一个手势,为触摸结束事件添加第二个手势。

以下是我的代码:-

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

点击手势只有一种状态 - "ended"。您无法检测到点击何时开始使用点击手势。如您所见,尝试使用两次点击手势无法达到您的要求。

您需要实施 UIResponder 方法 touchesBegantouchesEnded

您可能还想看看 UITapGestureRecognizer - 让它在触摸时工作,而不是触摸起来? .

问题已通过实施自定义手势解决。

文件:-MyGesture.h

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

文件:-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");
    }
}