按下时 UILongPressGestureRecognizer 被调用两次
我正在检测用户是否按下了 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
UILongPressGestureRecognizer 是一个连续事件识别器。您必须查看状态,看看这是事件的开始、中间还是结束,并采取相应的行动。即您可以在开始后丢弃所有事件,或者只根据需要查看运动。来自类参考:
现在你可以像这样跟踪状态
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:
Now You Can Track The State Like This
要检查 UILongPressGestureRecognizer 的状态,只需在选择器方法上添加 if 语句:
To check the state of the UILongPressGestureRecognizer just add an if statement on the selector method:
您需要检查正确的状态,因为每个状态都有不同的行为。您很可能需要
UIGestureRecognizerStateBegan
状态和UILongPressGestureRecognizer
。...
You need to check the correct state, since there are different behaviors for each state. Most likely you're going to need the
UIGestureRecognizerStateBegan
state with theUILongPressGestureRecognizer
....
斯威夫特5:
Swift 5:
试试这个:
Objective-C
Swift 2.2:
Just try this:
Objective-C
Swift 2.2:
下面是在 Swift 中处理它的方法:
Here's how to handle it in Swift:
您的手势处理程序接收每个手势状态的调用。因此您需要检查每个状态并将代码置于所需状态。
人们肯定更喜欢使用 switch-case 而不是 if-else :
your gesture handler receives call for each state of gesture. so you need to put a check for each state and put your code in required state.
One must prefer using switch-case over if-else :