永远不会调用CAAnimationDelegate委托(CAAnimationDelegate delegates are never called)

我用两个CAShapeLayer's做了一个简单的进度线。 动画工作正常,但从不调用CAAnimationDelegate animationDidStart和animationDidStop 。

这是我的代码:

class ProgressBar: UIView, CAAnimationDelegate { var bottomProgressBar = CAShapeLayer() var topProgressBar = CAShapeLayer() let animation = CABasicAnimation(keyPath: "strokeEnd") override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } func configure() { animation.delegate = self // setup the two layers } func animate(toValue: Double) { animation.duration = 1.0 animation.fromValue = 0 animation.toValue = toValue topProgressBar.strokeEnd = CGFloat(toValue) topProgressBar.animation(forKey: "animate") } func animationDidStart(_ anim: CAAnimation) { print("start") } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { print("stop") } }

animate方法被称为多次,值范围从0到1。

有谁知道为什么这些代表从未被称为?

I made a simple progress line using two CAShapeLayer's. Animation works correctly but the CAAnimationDelegate animationDidStart and animationDidStop are never called.

Here is my code:

class ProgressBar: UIView, CAAnimationDelegate { var bottomProgressBar = CAShapeLayer() var topProgressBar = CAShapeLayer() let animation = CABasicAnimation(keyPath: "strokeEnd") override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } func configure() { animation.delegate = self // setup the two layers } func animate(toValue: Double) { animation.duration = 1.0 animation.fromValue = 0 animation.toValue = toValue topProgressBar.strokeEnd = CGFloat(toValue) topProgressBar.animation(forKey: "animate") } func animationDidStart(_ anim: CAAnimation) { print("start") } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { print("stop") } }

animate method is called multiple times with values ranging from 0 to 1.

Does anyone know why these delegates are never called ?

最满意答案

编辑:添加正确的解决方案与下面的每条评论的链接

您正在调用topProgressBar。 动画(forKey:“animate”) ,它实际返回动画; 它没有启动它。 你应该调用layer.add(animation,forKey :)来代替

EDIT: add correct solution with links per comment below

You are calling topProgressBar.animation(forKey: "animate") which actually returns the animation; it doesn't start it. You should call layer.add(animation, forKey:) instead

更多推荐