I created a Swift 4 function extension to CALayer
for this, to which you can pass the starting and ending UIColor
s as well as the duration for the animation:
extension CALayer {
func animateBorderColor(from startColor: UIColor, to endColor: UIColor, withDuration duration: Double) {
let colorAnimation = CABasicAnimation(keyPath: "borderColor")
colorAnimation.fromValue = startColor.cgColor
colorAnimation.toValue = endColor.cgColor
colorAnimation.duration = duration
self.borderColor = endColor.cgColor
self.add(colorAnimation, forKey: "borderColor")
}
Note that for this to work, you should have already set a borderWidth
and then call animateBorderColor
:
yourView.layer.borderWidth = 1.5
yourView.layer.animateBorderColor(from: UIColor.green, to: UIColor.red, withDuration: 2.0)