问题描述
我只想在 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
})
}
}
解决方法
动画层需要使用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
}