2012-02-01 61 views
3

我有一個自定義滑塊類型的對象,我希望使其更加可用。目前我使用UIPanGestureRecognizertranslationInView使它工作。它工作得很好,但我希望有某種速度讓它感覺更有用。我已經嘗試了一些東西,但不能完全弄清楚如何正確實現速度changedLevel等式。使用velocityInView與UIPanGestureRecognizer

- (void)panDetected:(UIPanGestureRecognizer *)gesture { 

    CGPoint swipeLocation = [gesture locationInView:self.tableView]; 
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:swipeLocation]; 
    LevelCounterTableCell *swipedCell = (LevelCounterTableCell *)[self.tableView cellForRowAtIndexPath:indexPath]; 

    if([gesture state] == UIGestureRecognizerStateBegan) { 
     NSString *originalLevelString = swipedCell.levelNumber.text; 
     originalLevel = [originalLevelString intValue]; // int originalLevel 
    } 

    if ([gesture state] == UIGestureRecognizerStateChanged) { 

     CGFloat xTranslation = [gesture translationInView:[[gesture view] superview]].x; 
     CGFloat xVelocity = [gesture velocityInView: [[gesture view] superview]].x; 

     // Pan threshold is currently set to 8.0. 
     // 8.0 is a decent level for slow panning 
     // for fast panning 2.0 is more reasonable 
     changedLevel = ceilf((xTranslation/panThreshold) + originalLevel); // int changedLevel 

     // Raw velocity seems to go from around 3 (slow) 
     // to over 200 (fast) 
     NSLog(@"raw velocity = %f", xVelocity); 

     if (changedLevel >= 15 && changedLevel <= 100) { 
      swipedCell.levelNumber.text = [NSString stringWithFormat:@"%i", changedLevel]; 
      swipedCell.meter.frame = [self updateMeter: changedLevel]; 

     } 
    } 

    if ([gesture state] == UIGestureRecognizerStateEnded || [gesture state] == UIGestureRecognizerStateCancelled) { 
     if (changedLevel >= 15 && changedLevel <= 100) { 
      //... Save the values...    
     } 

    } 
} 

任何幫助將不勝感激。謝謝。

回答

5

根據我的經驗,平移手勢識別器的velocityInView:並不重要,直到用戶擡起手指並且識別器結束爲止。此時,您可以使用速度來計算動畫持續時間以移動視圖。

只需堅持translationInView:,直到stateUIGestureRecognizerStateEnded,然後使用velocityInView:爲任何屏幕視圖更改設置動畫效果。

+0

在這個例子中,我想用它來增加自定義滑塊的拖動速度。例如,如果用戶緩慢拖動,我想將當前值每5像素距離增加1,但如果用戶拖動速度更快,我想將當前值每5像素距離增加10。 – squarefrog 2012-02-28 09:25:07

相關問題