我正在尝试向Swift中的按钮添加彩色动画。使用nil forKey可以正常工作-但是当我命名时,它可以在一个屏幕上运行,但是在过渡到另一个屏幕的瞬间,我得到"Terminating app due to uncaught exception 'CALayerInvalidTree', reason: 'expecting model layer not copy: <Project.ButtonGradientLayer: 0x600002cc6be0>'"
此应用程序是为我们而开发的,我们现在正在做一些小的修改,因此我不完全了解完整代码体的细微差别,并且调试经验有限。我不确定从哪里开始跟踪问题。
由于编写代码的方式,动画被应用了很多(> 50)次,我想通过在创建动画时命名它并在重新应用之前检查它是否已经存在来防止破坏性能。
使用Swift 4.2运行Xcode 10.0
class SpinButtonView: BaseView {
//lots of other code
private var buttonLayer: ButtonGradientLayer {
// swiftlint:disable force_cast
return layer as! ButtonGradientLayer
}
override class var layerClass: AnyClass {
return ButtonGradientLayer.self
}
}
class ButtonGradientLayer: CAGradientLayer {
//Other code plus definition of colors
var isEnabled: Bool = true {
didSet {
updateColors()
}
}
override init(layer: Any) {
super.init(layer: layer)
prepare()
}
override init() {
super.init()
prepare()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepare()
}
private func prepare() {
updateColors()
startPoint = CGPoint(x: 0.5, y: 0)
endPoint = CGPoint(x: 0.5, y: 1)
}
private func updateColors() {
if !isEnabled {
removeAllAnimations()
colors = ButtonGradientLayer.disabledColors
}
else {
colors = ButtonGradientLayer.enabledColors
let animation = CABasicAnimation(keyPath: "colors")
animation.fromValue = ButtonGradientLayer.enabledColors
animation.toValue = ButtonGradientLayer.enabledColors2
animation.duration = 0.85
animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.93, 0.83, 0.1, 1.05)
animation.autoreverses = true
animation.repeatCount = Float.infinity
animation.isRemovedOnCompletion = false
//THIS IS THE LINE THAT IS GIVING ME TROUBLE:
add(animation, forKey: "buttonFlash")
//WHEN I DO THIS INSTEAD IT DOESN'T COMPLAIN:
//add(animation, forKey: nil)
}
}
}
add(animation,forKey:“ buttonFlash”)使其崩溃,但是执行add(animation,forKey:nil)可以正常工作。