How to animate borderColor change in swift

后端 未结 5 995
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 05:26

For some reason this isn\'t working for me:

let color = CABasicAnimation(keyPath: \"borderColor\")
color.fromValue = sender.layer.borderColor;
color.toValue          


        
5条回答
  •  自闭症患者
    2021-01-18 06:08

    I created a Swift 4 function extension to CALayer for this, to which you can pass the starting and ending UIColors 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)
    

提交回复
热议问题