Search code examples
iosuiimageviewcore-animationrotationcabasicanimation

How to get solution for stopping/resuming CABasicAnimation working?


I'm using CABasicAnimation for rotating UIImageView and I'm unable to resume paused animation. The animation starts in viewDidLoad method:

UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MyImage.png"]];
self.myImage = img;
[self.view addSubview:img];
[img release];
CABasicAnimation *fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
fullRotation.fromValue = [NSNumber numberWithFloat:0];
fullRotation.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
fullRotation.duration = 10;
fullRotation.repeatCount = LARGE_VAL;
[img.layer addAnimation:fullRotation forKey:@"360"];

I need to have non-stop repeatable animation that resumes when the view appears on screen. So I have read this post (here) and implemented solution provided my apple (solution) for stopping and resuming layer animation. So, I have used these methods:

-(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;
}

And I have added these methods to viewWillAppear and viewWillDisappear using and passing the layer of myImage property:

-(void)viewWillDisappear:(BOOL)animated{
    [self pauseLayer:self.myImage.layer];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self resumeLayer:self.myImage.layer];
}

The image does initial rotation when the view goes on screen. But then I'm putting some UIViewController on screen, then going back to the view with image rotation. The problem is the rotation of the image is not resumed when the view appears on screen. I have checked: my image UIImageView property is not nil, both viewWillDisappear and viewWillAppear methods get invoked. But the animation is not resuming. Did I something wrong, or missed something?


Solution

  • Workarounds, workarounds and workarounds. So far, the solution I have got working is to throw away the suggested solution for stoping/resuming layer animation :), to remove all the animations in viewWillDisappear:

    [self.myImage.layer removeAllAnimations];  
    

    and then to start a new animation in viewWillAppear. I know that I'm not resuming the old one but, in my case, it's not so visible to the humans eye, so I think I will be good.