我有一个UI组件(一个加载微调器),它具有无限的动画:
class MySpinner: UIView {
...
override var bounds: CGRect {
didSet {
updateLayers()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.addSublayer(self.animatedLayer)
self.updateLayers()
self.startAnimating()
}
private func updateLayers() {
//Set up path, stroke color and such
self.animatedLayer.frame = self.bounds
}
private func startAnimating() {
CATransaction.begin()
CATransaction.setDisableActions(true) //disable automatic animations by iOS
let endlessRotationAnimation = CAKeyframeAnimation(keyPath: "transform.rotation")
endlessRotationAnimation.values = [ 0.0, CGFloat(2.0 * .pi) ]
endlessRotationAnimation.keyTimes = [ 0.0, 1.0 ]
endlessRotationAnimation.repeatDuration = .infinity
endlessRotationAnimation.duration = 1.0
self.animatedLayer.add(endlessRotationAnimation, forKey: "rotationAnimation")
CATransaction.commit()
}
}
事实证明这是行不通的。我假设如果在将视图添加到窗口之前调用startAnimating()
,iOS将立即删除动画。如果我先将视图添加到视图层次结构中,然后调用startAnimating()
,则事情开始进行。
是否有办法防止iOS删除我的动画?还是有一些有关此行为的文档,我找不到任何文档?
我可以通过覆盖didMoveToWindow
来解决此问题。