2013-11-04 130 views
0

enter image description here我有一個UIButton,使用UIPanGestureRecognizer類在y軸上上下拖動。我正在使用這個而不是UISlider來實現垂直功能。 我想捕獲所有爲拖拽0和1之間的浮點值的按鈕向上和向下像一個UISlider將是從0的最小值限制爲最多1如何使用UIPanGestureRecognizer從y值獲得0和1之間的浮點值

我當前的代碼ISN」的捕獲正確的值。我怎樣才能解決這個問題:

- (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]; 
    } 
} 
+1

您可以設置最小和手動UI滑塊的最大值,然後除以他們根據你想要的靈敏度得到一個浮點數。 – ManicMonkOnMac

回答

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 
+0

完美。謝謝 –

0

我靠locationOfTouchtranslationInView)和手勢的不同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); 
     }]; 
    } 
} 
相關問題