iOS中识别双击事件的做法:
- 创建UITapGestureRecognizer对象,设置numberOfTapsRequired的值为2,
UITapGestureRecognizer *doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)]; doubleTapRecognizer.numberOfTapsRequired = 2; [self addGestureRecognizer:doubleTapRecognizer];
- action 函数
- (void)doubleTap:(UIGestureRecognizer *)gr { NSLog(@"Recognized Double Tap"); }
同一个UIView中,实现了touchesBegan函数
// 触摸开始 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"touch begin"); }
问题
双击后,查看日志.发现触摸事件发生的顺序如下:
2015-09-15 21:57:55.249 TouchTracker[20387:5622651] touch begin
2015-09-15 21:57:55.421 TouchTracker[20387:5622651] double tap
这是因为用户点击屏幕时,UIView会收到在touchesBegan:withEvent 消息。在UIGestureRecognizer识别出双击手势之前,UIView会收到touchesBegan:withEvent 消息;在识别UIGestureRecognizer识别出双击手势之后,UIGestureRecognizer会自行处理相关触摸事件,触摸事件所引起的UIResponder消息将不再发送给UIView。直到UIGestureRecognizer检测出点击手势已经结束,UIView才会重新受到UIResponder消息。
解决
需要在识别出点击手势之前,避免向UIView发送touchBegin:withEvent消息。delaysTouchesBegan值设为YES。
UITapGestureRecognizer * doubleTapRecognizer= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleTap:)]; doubleTapRecognizer.numberOfTapsRequired=2; doubleTapRecognizer.delaysTouchesBegan=YES; [self addGestureRecognizer:doubleTapRecognizer];
区别双击和单击
增加单次点击识别
// single tap UITapGestureRecognizer *tapRecognizer= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)]; [self addGestureRecognizer:tapRecognizer]; action函数 -(void)tap:(UIGestureRecognizer *) gr { NSLog(@"tap"); }
查看日志输出的时候,发现,点击两次的时候,UIView无法识别单击事件和双击事件。tap:和 doubleTap: 都会执行。
2015-09-15 22:36:02.441 TouchTracker[20631:5667414] tap
2015-09-15 22:36:02.600 TouchTracker[20631:5667414] double tap
因为双击事件包含两次单击事件,所以第一次点击被识别为单击事件。
解决方法
设置在单击后暂时不进行识别(稍作停顿),直到确定不是双击事件后再识别为单击事件。
// single tap UITapGestureRecognizer *tapRecognizer= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)]; [tapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer]; [self addGestureRecognizer:tapRecognizer];