我正在检测用户是否已按下2秒钟: ui
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; longPress.minimumPressDuration = 2.0; [self addGestureRecognizer:longPress]; [longPress release];
这是我处理长按的方式: spa
-(void)handleLongPress:(UILongPressGestureRecognizer*)recognizer{ NSLog(@"double oo"); }
当我按下2秒钟以上时,文本“ double oo”被打印两次。 为何是这样? 我该如何解决? code
您的手势处理程序会收到每种手势状态的呼叫。 所以,您须要检查每一个状态并将代码置于必需状态。 事件
必须使用switch-case而不是if-else: get
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; longPress.minimumPressDuration = 1.0; [myView addGestureRecognizer:longPress]; [longPress release];
-(void)handleLongPress:(UILongPressGestureRecognizer *)gesture { switch(gesture.state){ case UIGestureRecognizerStateBegan: NSLog(@"State Began"); break; case UIGestureRecognizerStateChanged: NSLog(@"State changed"); break; case UIGestureRecognizerStateEnded: NSLog(@"State End"); break; default: break; } }
这是在Swift中处理的方法: it
func longPress(sender:UILongPressGestureRecognizer!) { if (sender.state == UIGestureRecognizerState.Ended) { println("Long press Ended"); } else if (sender.state == UIGestureRecognizerState.Began) { println("Long press detected."); } }
Objective-C的 io
- (void)handleLongPress:(UILongPressGestureRecognizer*)sender { if (sender.state == UIGestureRecognizerStateEnded) { NSLog(@"Long press Ended"); } else if (sender.state == UIGestureRecognizerStateBegan) { NSLog(@"Long press detected."); } }
Swift 2.2: select
func handleLongPress(sender:UILongPressGestureRecognizer) { if (sender.state == UIGestureRecognizerState.Ended) { print("Long press Ended"); } else if (sender.state == UIGestureRecognizerState.Began) { print("Long press detected."); } }
UILongPressGestureRecognizer是连续事件识别器。 您必须查看状态以查看这是事件的开始,中间仍是结束,并采起相应的措施。 即,您能够在开始以后放弃全部事件,或者仅根据须要查看运动。 从类参考 : bug
长按手势是连续的。 当在指定时间段内(minimumPressDuration)按下了容许的手指数(numberOfTouchesRequired),而且触摸没有移动超出容许的移动范围(allowableMovement)时,手势即开始(UIGestureRecognizerStateBegan)。 每当手指移动时,手势识别器都会转换为“更改”状态,而且在任何手指抬起时手势识别器都会终止(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 } }
Swift 3.0:
func handleLongPress(sender: UILongPressGestureRecognizer) { if sender.state == .ended { print("Long press Ended") } else if sender.state == .began { print("Long press detected") }