Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pause a CABasicAnimation?

I have a basic spinning animation of the iPhone. Is there any way that I can "pause" the animation so that the position of the view will be maintained? I guess one way of doing this would be to cause the animation to "complete" instead of calling "remove" on it, how would I do that?

CABasicAnimation* rotationAnimation; rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2]; rotationAnimation.duration = 100; rotationAnimation.cumulative = YES; rotationAnimation.repeatCount = HUGE_VALF; rotationAnimation.removedOnCompletion = NO; rotationAnimation.fillMode = kCAFillModeForwards; [myView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"]; 
like image 975
mclaughj Avatar asked Feb 21 '10 18:02

mclaughj


2 Answers

Recently appeared Apple's technical note QA1673 describes how to pause/resume layer's animation.

Pause and resume animations listing is below:

-(void)pauseLayer:(CALayer*)layer {     CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];     layer.speed = 0.0;     layer.timeOffset = pausedTime; }  -(void)resumeLayer:(CALayer*)layer {     CFTimeInterval pausedTime = [layer timeOffset];     layer.speed = 1.0;     layer.timeOffset = 0.0;     layer.beginTime = 0.0;     CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;     layer.beginTime = timeSincePause; } 

Edit: iOS 10 introduced new API - UIViewPropertyAnimator that allows to handle animations more interactively, for example it makes easy to pause and resume animation or 'seek' it to some particular progress value.

like image 52
Vladimir Avatar answered Sep 22 '22 15:09

Vladimir


Answer For Swift 3:

Credits @Vladimir

Code:

 func pauseAnimation(){   let pausedTime = layer.convertTime(CACurrentMediaTime(), fromLayer: nil)   layer.speed = 0.0   layer.timeOffset = pausedTime }  func resumeAnimation(){   let pausedTime = layer.timeOffset   layer.speed = 1.0   layer.timeOffset = 0.0   layer.beginTime = 0.0   let timeSincePause = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime   layer.beginTime = timeSincePause } 
like image 34
Supratik Majumdar Avatar answered Sep 22 '22 15:09

Supratik Majumdar