Reputation: 1396
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?
Upvotes: 3
Views: 1102
Reputation: 3686
Swift 5
In a case where you want to fully remove the layer, and it is the only one you added, then this safe little bit of code will remove it completely.
self.layer.removeAllAnimations()
if let myLayer = self.layer.sublayers?.first {
myLayer.removeFromSuperlayer()
}
Upvotes: 0
Reputation: 131436
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.
Upvotes: 2