CABasicAnimation resets to initial value after animation completes

后端 未结 15 2535
闹比i
闹比i 2020-12-04 05:44

I am rotating a CALayer and trying to stop it at its final position after animation is completed.

But after animation completes it resets to its initial position.

15条回答
  •  死守一世寂寞
    2020-12-04 06:17

    This works:

    let animation = CABasicAnimation(keyPath: "opacity")
    animation.fromValue = 0
    animation.toValue = 1
    animation.duration = 0.3
    
    someLayer.opacity = 1 // important, this is the state you want visible after the animation finishes.
    someLayer.addAnimation(animation, forKey: "myAnimation")
    

    Core animation shows a 'presentation layer' atop your normal layer during the animation. So set the opacity (or whatever) to what you want to be seen when the animation finishes and the presentation layer goes away. Do this on the line before you add the animation to avoid a flicker when it completes.

    If you want to have a delay, do the following:

    let animation = CABasicAnimation(keyPath: "opacity")
    animation.fromValue = 0
    animation.toValue = 1
    animation.duration = 0.3
    animation.beginTime = someLayer.convertTime(CACurrentMediaTime(), fromLayer: nil) + 1
    animation.fillMode = kCAFillModeBackwards // So the opacity is 0 while the animation waits to start.
    
    someLayer.opacity = 1 // <- important, this is the state you want visible after the animation finishes.
    someLayer.addAnimation(animation, forKey: "myAnimation")
    

    Finally, if you use 'removedOnCompletion = false' it'll leak CAAnimations until the layer is eventually disposed - avoid.

提交回复
热议问题