0

在此处输入图像描述我有一个 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];
    }
}
4

2 回答 2

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
于 2013-11-04T21:00:36.117 回答
0

我依靠locationOfTouch( not 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);
        }];
    }
}
于 2013-11-04T20:46:09.993 回答