码迷,mamicode.com
首页 > 其他好文 > 详细

UIView-双击手势和单击手势的区别

时间:2015-10-19 00:32:58      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

iOS中识别双击事件的做法:

  1. 创建UITapGestureRecognizer对象,设置numberOfTapsRequired的值为2,
UITapGestureRecognizer *doubleTapRecognizer =

            [[UITapGestureRecognizer alloc] initWithTarget:self

                                                    action:@selector(doubleTap:)];

        doubleTapRecognizer.numberOfTapsRequired = 2;

        [self addGestureRecognizer:doubleTapRecognizer];

 

  1. 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];

 

UIView-双击手势和单击手势的区别

标签:

原文地址:http://www.cnblogs.com/sueZheng/p/4890706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!