在没有将 isRemovedOnCompletion 设置为 false 的情况下保留动画的 stokeEnd 更改

Preserving stokeEnd change from animation without isRemovedOnCompletion set to false

我有一个动画进度圈。我可以按下一个按钮,它会动画到 20%,如果我再次按下按钮,它就会动画到 40%。我正在将 isRemovedOnCompletion 设置为 false。但是,每次我执行动画时,都会将新动画添加到 CAShapelayer。我想这对性能不利。有更好的方法吗?

虚拟代码:

@IBAction func didTapAnimate(_ sender: Any) {
        let animateStroke = CABasicAnimation(keyPath: "strokeEnd")
        animateStroke.fromValue = index > 0 ? progressPts[index - 1] : 0
        animateStroke.toValue = progressPts[index]
        animateStroke.duration = 2.0
        animateStroke.fillMode = .forwards
        animateStroke.isRemovedOnCompletion = false
        circleLayer.add(animateStroke, forKey: "MyAnimation")
        index+=1
    }

只需调用 removeAnimation(forKey:"yourkey")

从 circleLayer 中删除之前的动画
@IBAction func didTapAnimate(_ sender: Any) {
        circleLayer.removeAnimation(forKey: "MyAnimation")
        let animateStroke = CABasicAnimation(keyPath: "strokeEnd")
        animateStroke.fromValue = index > 0 ? progressPts[index - 1] : 0
        animateStroke.toValue = progressPts[index]
        animateStroke.duration = 2.0
        animateStroke.fillMode = .forwards
        animateStroke.isRemovedOnCompletion = false
        circleLayer.add(animateStroke, forKey: "MyAnimation")
        index+=1
    }

据我所知,我认为不需要删除以前的动画只有一个动画层用于单个键,因此动画会自动替换为以前的动画。

A string that identifies the animation. Only one animation per unique key is added to the layer. The special key kCATransition is automatically used for transition animations. You may specify nil for this parameter.

所以只有最后一个动画占用内存,前一个动画自动释放。