长按手势执行两次解决办法

1、问题描述:
UILongPressGestureRecognizer为长按手势类, 与单击双击扫动等手势类似均继承自UIGestureRecognizer,但UILongPressGestureRecognizer在绑定View触发后,相对应的方法会执行两次?!

2、代理实现(关键代码)

1
2
3
4
5
6
7
8
9
10
11
UIView *view = [UIView alloc] init];
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTapAction:)];
[view addGestureRecognizer:longPress];
 
- (void)longTapAction:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        NSLog(@"long pressTap state :begin");
    }else {
        NSLog(@"long pressTap state :end");
    }
}

3、原因分析
从输出的打印来看,确实会调用两次,一次为长按开始后效时,一次为长按事件结束时调用,两次!如果只要一次,取其中一次执行事件即可!

Leave a Reply