如何使用UIPanGestureRecognizer从y值获取0到1之间的浮点值

时间:2013-11-04 20:02:14

标签: ios objective-c math

enter image description here我有一个UIButton,我使用UIPanGestureRecognizer类在y轴上上下拖动。我正在使用它而不是UISlider来实现垂直功能。 我希望捕获0和1之间的所有浮点值,因为像UISlider一样向上和向下拖动按钮将从最小值0限制到最大值1。

我当前的代码没有捕获正确的值。我该如何解决这个问题:

- (void)wasDragged:(UIPanGestureRecognizer *)recognizer {

    CGPoint translation = [recognizer translationInView:self.view];

    CGPoint newCenter = CGPointMake(recognizer.view.center.x,recognizer.view.center.y + translation.y);

    //range is 139 pixels

    //i tried dividing 1/139 to get the increment using pixels

    if(newCenter.y >= 126 && newCenter.y <= 265)
    {
        currentMainVolValue = currentMainVolValue - 0.00714285714286; 
        recognizer.view.center = newCenter;
        [recognizer setTranslation:CGPointZero inView:self.view];
    }
}

2 个答案:

答案 0 :(得分:1)

假设126是最小的y值,265是最大值。您需要从当前平移中减去最小的y,然后将结果除以范围

CGFloat minY  = 126;
CGFloat range = 256 - minY;

return 1 - ((yTranslation - minY) / range);

这给出了

yTranslation = 256 then value = 0
yTranslation = 126 then value = 1
yTranslation = 191 then value = 0.5

答案 1 :(得分:0)

我依靠locationOfTouch translationInView)和不同的state手势来实现类似的目标。

在我的情况下,我必须使用此子视图内的锚定按钮移动子视图(为UIPanGestureRecognizer注册的按钮)。一旦手势完成,我的视图将再次捕捉到屏幕的左侧墙(y轴移动)。

- (void)moveViewWithGestureRecognizer:(UIPanGestureRecognizer *)gestureRecognizer
{
    // Need to make below calculation for other orientations. Until then this is not allowed.
    if (self.interfaceOrientation != UIInterfaceOrientationPortrait) return;
    static CGFloat initialCenterPointX = 0;

    const CGPoint deltaPoint = CGPointMake(self.view.bounds.size.width/2 - gestureRecognizer.view.superview.center.x, self.view.bounds.size.height/2 - gestureRecognizer.view.superview.center.y);

    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        initialCenterPointX = self.view.center.x;
    }
    else if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
        CGPoint location = [gestureRecognizer locationOfTouch:0 inView:self.view];

        NSLog(@"gestureRecognizer.view = %@ location = %f, %f", gestureRecognizer.view, location.x, location.y);
        CGFloat proposedCenterPointX = self.view.frame.origin.x + location.x;
        CGFloat proposedCenterPointY = self.view.frame.origin.y + deltaPoint.y + location.y;

        CGPoint newCenterLocation = CGPointZero;

        newCenterLocation.x = MAX(proposedCenterPointX, self.view.bounds.size.width/2);
        newCenterLocation.y = MAX(proposedCenterPointY, self.view.bounds.size.height/2);

        self.view.center = newCenterLocation;
    }
    else {
        [UIView animateWithDuration:0.2 animations:^{
            self.view.center = CGPointMake(initialCenterPointX, self.view.center.y);
        }];
    }
}