【问题标题】:Start CAAnimation when view is not in view hierarchy当视图不在视图层次结构中时启动 CAAnimation
【发布时间】:2020-02-15 16:50:23
【问题描述】:

我有一个具有无限动画的 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 删除我的动画?还是有一些关于这种行为的文档,我找不到?

【问题讨论】:

    标签: ios uiview core-animation caanimation


    【解决方案1】:

    我可以通过覆盖 didMoveToWindow 来解决这个问题。

    public override func didMoveToWindow() {
        super.didMoveToWindow()
        startAnimating()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 2014-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多