我有一个分段控件,允许短手势和长手势。短手势识别很好。长手势方法被调用两次。我为此感到头疼。
这是构建颜色工具栏的代码的一部分:
UILongPressGestureRecognizer* longPressGestureRec =
[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
longPressGestureRec.minimumPressDuration = 1.5;
//longPressGestureRec.cancelsTouchesInView = NO;
[colorControl addGestureRecognizer:longPressGestureRec];
这是longPress方法的一部分:
-(void) longPress:(id)sender {
NSLog(@"%s", __FUNCTION__);
switch (colorIndex) {
case 0:
[self showMoreWhiteColors:(id)sender];
break;
case 1:
[self showMoreRedColors:(id)sender];
break;
通过查看日志,我可以看到每次按住按钮时都会调用longPress方法两次。
任何想法我做错了什么,失踪了,没有做....?
答案 0 :(得分:7)
我只是检查状态是否为UIGestureRecognizerStateBegan,否则在执行我想要的代码之前返回。所以:
-(void) longPressGesture:(UIGestureRecognizer*)gesture
{
if ( gesture.state != UIGestureRecognizerStateBegan )
return; // discard everything else
// do something in response to long gesture
}
答案 1 :(得分:3)
- (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
}
}
答案 2 :(得分:1)
或者你可以这样做。
-(void)handleLongPress:(UILongPressGestureRecognizer *)gesture {
switch(gesture.state){
case UIGestureRecognizerStateBegan:
// Do your stuff here.
NSLog(@"State Began");
break;
case UIGestureRecognizerStateChanged:
NSLog(@"State changed");
break;
case UIGestureRecognizerStateEnd:
NSLog(@"State End");
break;
default:
break;
}
}