UIPanGestureRecognizer以像素为单位获取滑动距离

时间:2014-12-17 07:59:51

标签: ios objective-c uipangesturerecognizer

我正在尝试跟踪用户使用UIPanGestureRecognizer刷过的水平距离,但是我难以解释结果。这是我正在使用的代码:

- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {

    CGPoint startLocation;

    if (recognizer.state == UIGestureRecognizerStateBegan) {
        startLocation = [recognizer locationInView:self.view];
    }

    if (recognizer.state == UIGestureRecognizerStateEnded) {
        CGPoint stopLocation = [recognizer locationInView:self.view];
        CGFloat dx = stopLocation.x - startLocation.x;
        NSLog(@"dx: %f", dx);
    }
}

如果我从左向右滑动,我会得到如下输出:

dx: 50328911327402404790403072.000000

我的屏幕只有320像素宽,所以我的最终结果不能超过320.我的代码是否有问题,或者我只是错误地解释了这个数字?如何以像素为单位显示此值?谢谢!

2 个答案:

答案 0 :(得分:3)

startLocation返回后,

handlePan:不会持续存在,因此您将获得垃圾。

startLocation声明为static或将其保存在实例变量/属性中。

答案 1 :(得分:0)

您可以使用UIPanGestureRecognizer,如下所示: -

CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];

if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {
    firstX = [[sender view] center].x;
    firstY = [[sender view] center].y;
}

translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY);

[[sender view] setCenter:translatedPoint];

if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {
    CGFloat velocityX = (0.2*[(UIPanGestureRecognizer*)sender velocityInView:self.view].x);


    CGFloat finalX = translatedPoint.x + velocityX;
    CGFloat finalY = firstY;