How to animate borderColor change in swift

Chase Roberts picture Chase Roberts · Mar 9, 2015 · Viewed 7.6k times · Source

For some reason this isn't working for me:

let color = CABasicAnimation(keyPath: "borderColor")
color.fromValue = sender.layer.borderColor;
color.toValue = UIColor.redColor().CGColor;
color.duration = 2;
color.repeatCount = 1;
sender.layer.addAnimation(color, forKey: "color and width");

I'm not getting any animation to occur.

Answer

budiDino picture budiDino · Nov 29, 2018

Swift 4 UIView extension:

extension UIView {
  func animateBorderColor(toColor: UIColor, duration: Double) {
    let animation:CABasicAnimation = CABasicAnimation(keyPath: "borderColor")
    animation.fromValue = layer.borderColor
    animation.toValue = toColor.cgColor
    animation.duration = duration
    layer.add(animation, forKey: "borderColor")
    layer.borderColor = toColor.cgColor
  }
}

And then just use it by writing:

myView.animateBorderColor(toColor: .red, duration: 0.5)