Layer animations removed when switching apps

2019-05-26 19:19发布

问题:

(iOS 5.0)

I have an CAKeyframeAnimation added to a view's layer with an infinite repeat count (a cursor blinking). However, when switching apps and coming back, the animation gets removed from the layer (or possibly the entire layer is replaced, I'm not sure).

I tried re-adding them on viewDidLoad and viewWillAppear, but neither is called when switching apps. I did find there is a applicationWillEnterForeground: method in UIApplicationDelegate. I'm planning to use this but I have two questions:

  • Are there any other circumstances that trigger the animations or layer to be unloaded? Is there a more appropriate event to listen to?
  • What is the best practice (in an design pattern sense) to respond to these events (e.g. using target action)?

回答1:

When switching apps or view controllers, the system will let the animations on the layer stop (complete), so you can set removedOnCompletion to NO (the default is YES), and it will work.



回答2:

You're correct that you'll have to again add the animations to the CALayer when the app comes again to the foreground.

You need to remove them when you receive the applicationWillResignActive callback. If desired, you can check the presentationLayer to get the currently rendered - or as near as - onscreen properties.

Then, when your app becomes active again as per the applicationDidBecomeActive callback, add the animations afresh.

Your app can move from active to inactive for a number of reasons, e.g. receiving a call, SMS, alarm, user presses home button, etc.

Have a look at my answer to this question where I cover some of the issues with resuming a CAAnimation:

Restoring animation where it left off when app resumes from background