2013-09-30 51 views
4

當使用UIPanGestureRecognizer並檢測UIGestureRecognizerStateEnded時,手勢的速度不是真實的速度。相反,這是以前調用我的操作方法的舊速度。我如何在手勢結束時訪問真實速度?如何確定平底手勢的真實最終速度?

創建我UIPanGestureRecognizer這樣的:

UIPanGestureRecognizer* panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognized:)]; 
    [panGestureRecognizer setMaximumNumberOfTouches:2]; 
    [panGestureRecognizer setMinimumNumberOfTouches:1]; 
    [panGestureRecognizer setDelegate:self]; 
    [panGestureRecognizer setDelaysTouchesBegan:NO]; 
    [panGestureRecognizer setDelaysTouchesEnded:NO]; 
    [panGestureRecognizer setCancelsTouchesInView:NO]; 
    [self addGestureRecognizer:panGestureRecognizer]; 

我的行動方法的開始是在這裏:日誌輸出的

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

    UIGestureRecognizerState state = recognizer.state; 

    CGPoint gestureTranslation = [recognizer translationInView:self]; 
    CGPoint gestureVelocity = [recognizer velocityInView:self]; 

    [CBAppDelegate log:@"panGestureRecognized: state: %s\n translation: (%f, %f)\n velocity: (%f, %f)", [self toString:state], gestureTranslation.x, gestureTranslation.y, gestureVelocity.x, gestureVelocity.y]; 

例子:

2013-09-30_10:46:32.830 panGestureRecognized: state: UIGestureRecognizerStateChanged 
    translation: (-283.000000, 2.000000) 
    velocity: (-43.046783, 45.551472) 
2013-09-30_10:47:02.942 panGestureRecognized: state: UIGestureRecognizerStateEnded 
    translation: (-283.000000, 2.000000) 
    velocity: (-43.046783, 45.551472) 

,你可以看,兩個日誌條目的速度是一樣的(同樣的故事與翻譯,但我只關心速度),儘管我沒有移動手指約30秒,然後擡起手指。您可以根據條目的時間戳來確定時間。在不移動我的手指30秒後,肯定不會有速度報告。

我已經用iOS 6.1的iOS模擬器對iPhone進行了測試。

+0

就可以計算出自己與時間戳。長時間擱置,如果開始時間戳足夠長,則可以重置開始時間戳,然後根據需要計算任何內容。祝你好運! –

回答

17

velocityInView方法僅在發生平移時定義。也就是說,只有當你實際移動手指時,平移手勢纔會發生。如果你保持手指靜止,它實際上不會觸發平移手勢。

這意味着手勢結束時沒有內置的方法來知道移動速度。你可以做一些事情,例如檢查最後一次事件與狀態值之間的時間差異爲UIGestureRecognizerStateChangedUIGestureRecognizerStateEnded。然後,您可以調整此閾值以獲得所需的行爲。

例如

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

    UIGestureRecognizerState state = recognizer.state; 

    CGPoint gestureTranslation = [recognizer translationInView:self]; 
    CGPoint gestureVelocity = [recognizer velocityInView:self]; 

    if (state == UIGestureRecognizerStateChanged) 
     _lastChange = CFAbsoluteTimeGetCurrent(); 
    else if (state == UIGestureRecognizerStateEnded) { 
     double curTime = CFAbsoluteTimeGetCurrent(); 
     double timeElapsed = curTime - _lastChange; 
     if (timeElapsed < MY_THRESHOLD) 
       finalSpeed = gestureVelocity; 
     else 
       finalSpeed = CGPointZero; 
    } 
} 
+0

謝謝。我已經實現了這一點,它的工作原理。 :) –

+1

偉大的答案!我能知道你爲MY_THRESHOLD設定了什麼價值嗎? – Atul

+0

恐怕我只是爲這個問題創建了這個玩具的例子,我實際上並不需要自己使用它!你也許可以玩不同的值,看看哪一個最好用 – micantox