试图获得触摸点,返回NaN

时间:2011-12-03 12:14:35

标签: iphone objective-c location touch uigesturerecognizer

好的,我在这里遇到了一个非常奇怪的问题。我的视图中有一个150x150的按钮,我在该按钮上添加了UILongPressGestureRecognizer,因为我需要按下按钮时按下按钮的位置。我这样做的代码如下:

-(CGPoint)detectedTouch:(UILongPressGestureRecognizer *)sender { 

    CGPoint touchPoint = [sender locationInView:button];
    return touchPoint;
}


-(void)myAction {

    CGPoint touchPoint = [self detectedTouch:myGestureRecognizer];  
    NSLog(@"touchPoint = %f, %f", touchPoint.x, touchPoint.y);

    //do stuff
}

现在当按钮处于普通视图时,一切正常。但是当按钮位于scrollView上时,它只有在您按下它大约一秒钟时才有效。如果你发布得太快,日志会给我这个:

touchPoint = nan, nan

非常感谢任何解决此问题的帮助!

2 个答案:

答案 0 :(得分:2)

UIGestureRecognizer在其生命周期中有各种状态,例如可能,已识别,失败,已结束,已取消。我会尝试在你的识别器方法中放置一个switch语句,然后看看哪个正在发生以更好地缩小问题范围。它看起来像这样:

switch (sender.state){
    case  UIGestureRecognizerStatePossible:
        NSLog(@"possible");
        break;
    case  UIGestureRecognizerStateFailed:
        NSLog(@"Failed!");
        break;
    ... All Cases wanted
    default:
        break;
}

我不知道内部细节,但也许如果失败/取消它不会在视图中选取位置。

以下是关于手势识别器的子类化以及可能发生的状态的文档。

http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UIGestureRecognizer_Class/Reference/Reference.html

答案 1 :(得分:0)

我试图重现你的问题,但没有成功。起初,我认为手势识别器可能会干扰scrollView滚动手势识别器,但似乎并非如此。这是我的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongHold:)];
//    [scrollView addGestureRecognizer:recognizer];
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 2000)];
    lbl.text = @"lorem ipsum......";
    lbl.numberOfLines = 0;
    scrollView.contentSize = CGSizeMake(lbl.frame.size.width, lbl.frame.size.height);
    [scrollView addSubview:lbl];
    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(0, 0, 150, 150);
    [btn addGestureRecognizer:recognizer];
    [scrollView addSubview:btn];

    v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    v.backgroundColor = [UIColor yellowColor];
    v.hidden = YES;
    [scrollView addSubview:v];
}

- (void) handleLongHold:(UILongPressGestureRecognizer*) recognizer {
    NSLog(@"long tap handled");
    v.hidden = NO;
    v.center = [recognizer locationInView:btn];
}

顺便说一下,我偶然发现了一个问题,想找到一种从手势识别器选择器中找到触摸点的方法 - locationInView方法帮助了我,希望这段代码可以帮助你。