iOS处理单双击手势冲突问题

这个是之前开发中遇到的一个问题. 当一个视图同时响应单双击手势, 而实际上需要它只响应一个手势就行; 这种情况当手势同时加在一个视图上或者两个视图的关系为父子级时出现, 下面就来介绍一下处理的方法;
这里展示一个demo:
如图所示, 在storyboard中拖入两个view, 分别为bigView和smallView, smallView为bigView的子视图;


接下来给这两个视图拖入属性后, 给smallView加上单击事件, bigView加上双击事件;

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *bigView;
@property (weak, nonatomic) IBOutlet UIView *smallView;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleTap:)];
[singleTapGestureRecognizer setNumberOfTapsRequired:1];
[_smallView addGestureRecognizer:singleTapGestureRecognizer];
UITapGestureRecognizer *doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleTap:)];
[doubleTapGestureRecognizer setNumberOfTapsRequired:2];
[_bigView addGestureRecognizer:doubleTapGestureRecognizer];
}
- (void)singleTap:(UIGestureRecognizer*)gestureRecognizer
{
NSLog(@"-----singleTap-----");
[_smallView setBackgroundColor:[UIColor yellowColor]];
}
- (void)doubleTap:(UIGestureRecognizer*)gestureRecognizer
{
NSLog(@"-----doubleTap-----");
[_bigView setBackgroundColor:[UIColor redColor]];
}

接下来如果双击smallView, 你会发现视图变成下面这样:


本来双击只加载在smallView的父视图bigView上, 结果smallView也响应了, 这就尴尬了😓了;
处理方式其实挺简单, 只不过最开始找了好久;
下面贴出代码:(在viewDidLoad方法末尾添加)

1
2
//这行很关键,意思是只有当没有检测到doubleTapGestureRecognizer或者检测doubleTapGestureRecognizer失败,singleTapGestureRecognizer才有效
[singleTapGestureRecognizer requireGestureRecognizerToFail:doubleTapGestureRecognizer];

好了, 完美解决(^__^) 嘻嘻……

-------------文章结束标记O(∩_∩)O哈哈~-------------
知我者谓我心忧