IOS:使用手势计算两个cgpoint的距离

时间:2012-02-22 14:34:12

标签: ios xcode distance cgpoint uipangesturerecognizer

我在视图中有手势代码

- (void)rightSwipeHandle:(UIPanGestureRecognizer*)gestureRecognizer{

    CGPoint touchBegan;
    CGPoint pointEnd;

    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) 
    {   
        CGPoint touchBegan = [gestureRecognizer locationInView: gestureRecognizer.view];
        NSLog(@"pointBegan:%@",NSStringFromCGPoint(touchBegan));
    }
    else if (gestureRecognizer.state == UIGestureRecognizerStateChanged)
    {
    }

    else if (gestureRecognizer.state == UIGestureRecognizerStateEnded     ||
             gestureRecognizer.state == UIGestureRecognizerStateCancelled ||
             gestureRecognizer.state == UIGestureRecognizerStateFailed)
    {   
        pointEnd = [gestureRecognizer locationInView:gestureRecognizer.view];
        NSLog(@"pointEnd:%@", NSStringFromCGPoint(pointEnd));

        CGFloat xDist = (pointEnd.x - touchBegan.x);
        CGFloat yDist = (pointEnd.y - touchBegan.y);
        CGFloat distance = sqrt((xDist * xDist) + (yDist * yDist));
        NSLog(@"distance:%f", distance);
    }


}

但它不能正常工作,我不知道问题出在哪里...... 如果滑动是从底部到顶部,它计算距离,如果你做相反的事情,它计算一个很大的不同距离,我不明白

1 个答案:

答案 0 :(得分:5)

将点定义为静态,否则touchBegan点将失去其值。之所以发生这种情况,是因为设置每个点的值发生在不同的方法调用中,并且每一个都在一开始就重新定义了这些点。

static CGPoint touchBegan;
static CGPoint pointEnd;