Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate borderColor change in swift

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.

like image 349
Chase Roberts Avatar asked Mar 09 '15 03:03

Chase Roberts


2 Answers

(Swift 5, Xcode 11, iOS 13)

For anyone who is wanting to change border color and width at the same time, the following code is working for me & the animation looks very smooth. Maybe someone else knows of a way to combine both into one?

let borderColorAnimation: CABasicAnimation = CABasicAnimation(keyPath: "borderColor")
borderColorAnimation.fromValue = layer.borderColor
borderColorAnimation.toValue = toColor.cgColor
borderColorAnimation.duration = animationDuration
layer.add(borderColorAnimation, forKey: "borderColor")
layer.borderColor = toColor.cgColor

let borderWidthAnimation: CABasicAnimation = CABasicAnimation(keyPath: "borderWidth")
borderWidthAnimation.fromValue = layer.borderWidth
borderWidthAnimation.toValue = toWidth
borderWidthAnimation.duration = animationDuration
layer.add(borderWidthAnimation, forKey: "borderWidth")
layer.borderWidth = toWidth
like image 174
Trev14 Avatar answered Oct 10 '22 13:10

Trev14


Swift 4 UIView extension:

extension UIView {
  func animateBorderColor(toColor: UIColor, duration: Double) {
    let animation = 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)
like image 23
budiDino Avatar answered Oct 10 '22 13:10

budiDino