ios - 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
})
}
}
解决方案
动画层需要使用 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
}
推荐阅读
- swift - Homekit 触发器,如何调用
- spring-mvc - SpringMVC,属性'driverClassName'抛出java.lang.IllegalStateException:无法加载驱动程序类oracle.jdbc.driver.OracleDriver
- java - 如何在 Java SE 中激活自动 JPA 实体验证?
- unity3d - Google Play 游戏未登录(不显示弹出窗口)
- python - Kivy 自定义动画功能
- android - 如何避免 Animator 动画的加速/减速?
- python - 如何将格式化句子数组传递给 Flask 模板?
- javascript - 当用户在地址栏 Angular 上单击输入时检测事件
- php - 在 Laravel 中更新大量条目的最佳方法
- powershell - 在 Windows 10 上通过 ssh 在 cygwin 上获得 rsync 的神奇组合