我正在检测用户是否按下了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”将被打印两次。 为什么是这样? 如何解决?
I am detecting if the user has pressed down for 2 seconds:
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; longPress.minimumPressDuration = 2.0; [self addGestureRecognizer:longPress]; [longPress release];This is how I handle the long press:
-(void)handleLongPress:(UILongPressGestureRecognizer*)recognizer{ NSLog(@"double oo"); }The text "double oo" gets printed twice when I press down for longer than 2 seconds. Why is this? How can I fix?
最满意答案
UILongPressGestureRecognizer是一个连续的事件识别器。 你必须看状态,看看这是事件的开始,中间还是结束,并相应地采取行动。 即,您可以在开始之后丢弃所有事件,或者只根据需要查看运动。 从课堂参考 :
长按手势是连续的。 当允许的手指数(numberOfTouchesRequired)被按下指定的时间段(minimumPressDuration)时,手势开始(UIGestureRecognizerStateBegan),触摸不会超出允许的移动范围(allowedMovement)。 当手指移动时,手势识别器将转换到“更改”状态,并且当任何手指松开时,手势识别器将结束(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 } }UILongPressGestureRecognizer is a continuous event recognizer. You have to look at the state to see if this is the start, middle or end of the event and act accordingly. i.e. you can throw away all events after the start, or only look at movement as you need. From the Class Reference:
Long-press gestures are continuous. The gesture begins (UIGestureRecognizerStateBegan) when the number of allowable fingers (numberOfTouchesRequired) have been pressed for the specified period (minimumPressDuration) and the touches do not move beyond the allowable range of movement (allowableMovement). The gesture recognizer transitions to the Change state whenever a finger moves, and it ends (UIGestureRecognizerStateEnded) when any of the fingers are lifted.
Now You Can Track The State Like This
- (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 } }更多推荐
发布评论