【问题标题】:UIView animate not working on UIView's layersUIView 动画不适用于 UIView 的图层
【发布时间】:2021-05-22 19:16:22
【问题描述】:

我只想在 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
        })

    }
}

【问题讨论】:

    标签: ios swift animation uiview calayer


    【解决方案1】:

    要动画层需要使用 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
        }
    

    【讨论】:

    • 可能希望colorAnimation.repeatCount = .greatestFiniteMagnitude(无限重复)和colorAnimation.autoreverses = true 循环往复颜色。
    • @DonMag 你是对的,有问题的动画函数错过了选项数组。谢谢,已添加
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    相关资源
    最近更新 更多