2014-03-26 34 views
0

我有一個帶背景圖像的按鈕,當應用程序運行時我希望按鈕旋轉,當應用程序轉到背景時,按鈕應該停止旋轉。從上一個位置暫停和恢復動畫

我打電話給無限旋轉按鈕的方法startSpiningAnimation
當應用程序轉到後臺時,我呼叫stopSpinningAnimation停止旋轉動畫。

- (void)startSpiningAnimation { 
    [self stopSpinningAnimation]; 

    CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; 
    animation.fromValue = [NSNumber numberWithFloat:0.0]; 
    animation.toValue = [NSNumber numberWithFloat: 2*M_PI]; 
    animation.duration = 10.0f; 
    animation.repeatCount = INFINITY; 
    [self.button.layer addAnimation:animation forKey:@"SpinAnimation"]; 
} 

- (void)stopSpinningAnimation { 
    [self.button.layer removeAllAnimations]; 
}  

- (void)handleApplicationDidBecomeActiveNotification:(NSNotification *)not { 
    [self startSpiningAnimation]; 
} 

- (void)handleApplicationWillResignActiveNotification:(NSNotification *)not { 
    [self stopSpinningAnimation]; 
} 

一切都很正常我唯一的問題是,每一個應用程序來前景和動畫啓動時,它從原來的位置開始。

(我完全理解爲什麼會發生,當應用程序被切換到後臺obesely我刪除所有動畫..我只是不知道如何解決這個問題)

我想是該按鈕旋轉動畫將繼續從最後一個角度來看。

+1

[有沒有辦法暫停CABasicAnimation?](http://stackoverflow.com/questions/2306870/is-there-a-way-to-pause-a-cabasicanimation) –

回答

0

您可以收集update()方法中的所有'動態'行爲,該方法僅在應用程序處於前景時纔會調用。

因此,您將有創建,更新和停止動畫的方法。當您的應用程序離焦時,不再調用更新,並且動畫不再更新。但它仍然存在,並且相關變量將保留在先前的狀態中。