美文网首页
如何给同一个视图添加两种手势且避免冲突

如何给同一个视图添加两种手势且避免冲突

作者: 百事星空 | 来源:发表于2018-02-07 20:03 被阅读18次

    引言

    开发过程中可能会遇到这样的需求,同一个view既可以点击也可以长按,这个时候你可能会想到直接添加两个手势不就行了,可是事实未必是你想的那样。
    废话不多说直接上代码:

    1.创建view 并添加手势

    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, 300, 300);
    
    //添加点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    tap.delegate = self;
    [view addGestureRecognizer:tap];
    //添加长按手势
    UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pressAction:)];
    longPress.minimumPressDuration = 0.8;//长按手势的触发事件
    longPress.delegate = self;
    [view addGestureRecognizer: longPress];
    
    //重点!!! 如果长按确定偵測失败才會触发单击
    [tap requireGestureRecognizerToFail:longPress];
    

    2.代理方法

     // 允许多个手势并发
     - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
         return YES;
     }
    

    3.手势的响应

    //点击
    -(void)tapAction:(UITapGestureRecognizer*)tap{
          //在此添加点击要实现的操作。。。
     }
    //长按
    -(void)pressAction:(UILongPressGestureRecognizer*)longPress{
     
       if (longPress.state == UIGestureRecognizerStateBegan) {
            NSLog(@"UIGestureRecognizerStateBegan");
            //添加个定时器使长按响应持续
           self.timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(timerSelector) userInfo:nil repeats:YES];
       }else if (longPress.state == UIGestureRecognizerStateChanged) {
     
       }else {//longPress.state == UIGestureRecognizerStateEnded
         [self.timer invalidate];
         self.timer = nil;
       }
     
     }
    //定时器响应
    -(void)timerSelector{
        //在此添加长按要实现的操作。。。
    }
    

    相关文章

      网友评论

          本文标题:如何给同一个视图添加两种手势且避免冲突

          本文链接:https://www.haomeiwen.com/subject/rgvazxtx.html