Search code examples
ios5core-animationsegue

iOS Core Animation fails after segue / view transition


I have a basic animation, simply rotating an image, I'm using Core Animation. In the viewWillAppear method I create the animation:

gearRotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
gearRotate.repeatCount = HUGE_VALF;
gearRotate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
gearRotate.duration = 2;
gearRotate.fromValue = 0;
gearRotate.toValue = [NSNumber numberWithFloat:(360*M_PI)/180];
[gearButton.imageView.layer addAnimation:gearRotate forKey:@"transform.rotation"];


[self stopGear];

I'm calling stopGear initially to pause the animation. I did have this code in viewDidLoad to start with. Anyway, when the animation is called it works fine:

-(void)startGear {
CFTimeInterval pausedTime = [gearButton.imageView.layer timeOffset];
gearButton.imageView.layer.speed = 1.0;
gearButton.imageView.layer.timeOffset = 0.0;
gearButton.imageView.layer.beginTime = 0.0;
CFTimeInterval timeSincePause = [gearButton.imageView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
gearButton.imageView.layer.beginTime = timeSincePause;

}

And this pause method works fine too:

-(void)stopGear {
CFTimeInterval pausedTime = [gearButton.imageView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
gearButton.imageView.layer.speed = 0.0;
gearButton.imageView.layer.timeOffset = pausedTime;

}

However, this all fails if I segue to another view then back to the main view. The app runs fine but the animation will never run if I've been to another view.

This is why I initially moved this code to viewWillAppear, thinking I needed to re-create my animation, but no beans. Any ideas?

Thanks.


Solution

  • OK, so I solved this by re-thinking how animations work. I'm now simply creating the animation each time I want it to run:

    -(void)startGear {
        gearRotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        gearRotate.repeatCount = HUGE_VALF;
        gearRotate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
        gearRotate.duration = 2;
        gearRotate.fromValue = 0;
        gearRotate.toValue = [NSNumber numberWithFloat:(360*M_PI)/180];
        [[gearButton.imageView layer] addAnimation:gearRotate forKey:@"transform.rotation"];
    

    }

    And when I want to pause it, I simply remove it:

    -(void)stopGear {
        [[gearButton.imageView layer] removeAnimationForKey:@"transform.rotation"];
    

    }

    I'm not sure currently if this is the Apple preferred method, but it works solidly.