I want to animate several properties of several subviews using Core Animations
in Swift
. I'm looking for a way to group the animations together and handle them as one, mainly to be able to synchronise them altogether and pause and resume all of them together, but also in order to avoid code duplication and make the code cleaner.
I tried to use other kind of animations, such as UIView.animate
or UIViewPropertyAnimator
, but neither of them fit my needs because they don't allow the customization needed for my case.
For now, I'm using CATransaction
to ensure that the animation changes are committed to Core Animation at the same time:
CATransaction.begin()
CATransaction.setAnimationDuration(1.5)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(controlPoints: 0.85, 0, 0.15, 1))
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fromValue = 0
opacityAnimation.toValue = 1.0
opacityAnimation.repeatCount = .infinity
opacityAnimation.autoreverses = true
self.lable.layer.add(beforeOpacityAnimation, forKey: "opacityAninmation")
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.fromValue = 1.5
scaleAnimation.toValue = 1.0
scaleAnimation.repeatCount = .infinity
scaleAnimation.autoreverses = true
self.imageView.layer.add(targetImageScaleAnimation, forKey: "scaleAnimator")
CATransaction.commit()
So far so good. But now I want to be able to pause and resume all animations together. From what I see here, in order to achieve this one would need to iterate over all animated layers (e.g. self.lable.layer
, self.imageView.layer
) to modify their speed
, timeOffset
and beginTime
properties (this is kinda dirty and nonatomic).
Is there a way to group these animations or refer to them as one in order to pause and resume them altogether?
If not, should I at least put these iterations over layers inside a CATransaction
as well?