我正在检测用户是否按下了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”会打印两次。为什么会这样?我该如何解决?
您需要检查正确的状态,因为每个状态都有不同的行为。你很可能需要UIGestureRecognizerStateBegan状态和UILongPressGestureRecognizer。
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
initWithTarget:self
action:@selector(handleLongPress:)];
longPress.minimumPressDuration = 1.0;
[myView addGestureRecognizer:longPress];
[longPress release];
...
- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture {
if(UIGestureRecognizerStateBegan == gesture.state) {
// Called on start of gesture, do work here
}
if(UIGestureRecognizerStateChanged == gesture.state) {
// Do repeated work here (repeats continuously) while finger is down
}
if(UIGestureRecognizerStateEnded == gesture.state) {
// Do end work here when finger is lifted
}
}
您的手势处理程序接收每个手势状态的调用。因此,您需要对每个状态进行检查,并将代码置于必需状态。
一个人肯定更喜欢使用switch-case而不是if-else:
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;
}
}