0

I want to animate shadow properties for a view. Initially I tried:

func animateIn(delay: TimeInterval = 0) {
        UIView.animate(withDuration: 0.2, delay: delay, options: .allowUserInteraction, animations: {
            self.shadowView.layer.shadowColor = UIColor.black.cgColor
            self.shadowView.layer.shadowOffset = CGSize(width: 15, height: 15)
            self.shadowView.layer.shadowRadius = 20
            self.shadowView.layer.shadowOpacity = 0.2
            self.layoutIfNeeded()
        }, completion: nil)
    }

which doesnt work given that UIView.animate doesnt work with layers.

I tested the following post (How to animate layer shadowOpacity?), but it only specifies how to animate the shadow Opacity. Is there any way to animate all my shadow properties like I would with an animation blocl?

Jacobo Koenig
  • 11,728
  • 9
  • 40
  • 75

1 Answers1

0

You are very close, you just create multiple CABasicAnimations for all the property changes and then you can use CAAnimationGroup

So let say you have 2 CABasicAnimation animations like:

let shadownOpacityAnimation = CABasicAnimation(keyPath: "shadowOpacity")
...
let shadowRadiusAnimation = CABasicAnimation(keyPath: "shadowRadius")
...

Then you can add them using CAAnimationGroup

let group = CAAnimationGroup()
group.duration = 0.2
group.repeatCount = 1
group.autoreverses = false
group.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
group.animations = [shadownOpacityAnimation, shadowRadiusAnimation]
layer.add(group, forKey: "allAnimations")

You can read more about it in this answer:

How can I create an CABasicAnimation for multiple properties?

Ladislav
  • 7,223
  • 5
  • 27
  • 31