我正在检测用户是否按下了 2 秒:
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; longPress.minimumPressDuration = 2.0; [self addGestureRecognizer:longPress]; [longPress release];
这就是我处理长按的方式:
-(void)handleLongPress:(UILongPressGestureRecognizer*)recognizer{ NSLog(@"double oo"); }
当我按下超过 2 秒时,文本“double oo”会打印两次。为什么是这样?我该如何解决?
UILongPressGestureRecognizer 是一个连续事件识别器。您必须查看状态,看看这是事件的开始、中间还是结束,并采取相应的行动。即,您可以在开始后丢弃所有事件,或者仅根据需要查看运动。从 类参考:
长按手势是连续的。当允许的手指数量 (numberOfTouchesRequired) 在指定的时间 (minimumPressDuration) 内被按下并且触摸没有超出允许的移动范围 (allowableMovement) 时,手势开始 (UIGestureRecognizerStateBegan)。每当手指移动时,手势识别器就会转换到 Change 状态,并在任何手指抬起时结束 (UIGestureRecognizerStateEnded)。
现在您可以像这样跟踪状态
- (void)handleLongPress:(UILongPressGestureRecognizer*)sender { if (sender.state == UIGestureRecognizerStateEnded) { NSLog(@"UIGestureRecognizerStateEnded"); //Do Whatever You want on End of Gesture } else if (sender.state == UIGestureRecognizerStateBegan){ NSLog(@"UIGestureRecognizerStateBegan."); //Do Whatever You want on Began of Gesture } }