Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset CALayer drawings / animations

I have some CALayer animations inside a subclass of UIView which start at a certain angle according to the current time when they get drawn for the first time. The problem is, that the animations will just resume at the last position when the app comes back from standby. Is it possible to detect this and somehow tell the draw(_:) method of the UIView to reset all the layers and animations and draw everything again with the new parameters?

like image 934
hoan Avatar asked Nov 18 '25 09:11

hoan


1 Answers

You can certainly call removeAllAnimations() on the layer in your app delegate applicationDidBecomeActive(_:) method to remove all animations.

(Actually it's probably cleaner to have your view controller register for UIApplicationDidBecomeActive notifications. That way you don't have to struggle with having your app delegate worry about notifying the front view controller that it should remove animations.)

That code might look like this:

NotificationCenter.default.addObserver(self, 
  selector: #selector(yourSelector(_:)), 
  name: .UIApplicationDidBecomeActive, object: nil)

If you haven't changed the underlying property you are animating then that will remove your animations and restore your layer and it's sublayers to their pre-animation state. (CALayer animation does not actually change the layer it's animating. It creates a "presentation layer" that draws the animation, and unless you've set isRemovedOnCompletion=true on your CAAnimation, the presentation layer is removed once the animation is complete and the layer reverts to it's starting state. It's pretty common to set a layer's property to it's ending state before submitting the animation so that once the animation completes, the underlying layer is left in the same state that it is in at the end of the animation.)

If you have changed the property/properties you are animating then you'll need to save their starting state and reset them to that state in your applicationDidBecomeActive(_:) method.

like image 92
Duncan C Avatar answered Nov 20 '25 23:11

Duncan C