首页 > 解决方案 > UIView 动画不适用于 UIView 的图层

问题描述

我只是想在 UIView 周围闪烁一个红色边框,然后反复淡出以清除。但是, UIView animate 方法似乎不起作用。

阻止 UIView 动画工作的层有什么特别之处吗?

public class MyAlertView: UIView {

    convenience init(args: [String]) {
        self.init(frame: CGRect.zero)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit() {
        self.translatesAutoresizingMaskIntoConstraints = false
        
        self.layer.cornerRadius = 10
        
        self.layer.borderColor = UIColor.systemRed.cgColor
        self.layer.borderWidth = 2.5
        
        UIView.animate(withDuration: 0.5, delay: 0.0, options: [.curveEaseInOut, .repeat, .autoreverse], animations: {
            self.layer.borderColor = UIColor.clear.cgColor
        })

    }
}

标签: iosswiftanimationuiviewcalayer

解决方案


动画层需要使用 CAAnimations 你可以使用这个扩展

extension CALayer {
   func addLoopBorderAnimation(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
       colorAnimation.repeatCount = .greatestFiniteMagnitude
       colorAnimation.autoreverses = true
       self.borderColor = endColor.cgColor
    self.add(colorAnimation, forKey: "borderColor")
  }
}

并打电话

     private func commonInit() {
        self.translatesAutoresizingMaskIntoConstraints = false
        
        self.layer.cornerRadius = 10
        
        self.layer.borderColor = UIColor.systemRed.cgColor
        self.layer.borderWidth = 2.5
        self.layer.addLoopBorderAnimation(from: UIColor.systemRed, to: UIColor.clear, withDuration: 0.5
    }

推荐阅读