当您离开应用程序时,所有动画都会从它们的图层中删除:系统会在每个图层上调用 removeAllAnimations。所以如果你想继续动画,那么你可以听 UIApplicationDidBecomeActiveNotification 并重新开始动画。
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
if (![_imageLeft.layer animationForKey:@"SpinAnimation"])
{
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.fromValue = [NSNumber numberWithFloat: 2*M_PI];
animation.toValue = [NSNumber numberWithFloat:0.0f];
animation.duration = 4.0f;
animation.repeatCount = INFINITY;
[_imageLeft.layer addAnimation:animation forKey:@"SpinAnimation"];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAnimation:) name:UIApplicationDidBecomeActiveNotification object:nil];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)addAnimation:(NSNotification *)notificaiton
{
if (_imageLeft && ![_imageLeft.layer animationForKey:@"SpinAnimation"])
{
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.fromValue = [NSNumber numberWithFloat: 2*M_PI];
animation.toValue = [NSNumber numberWithFloat:0.0f];
animation.duration = 4.0f;
animation.repeatCount = INFINITY;
[_imageLeft.layer addAnimation:animation forKey:@"SpinAnimation"];
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}