2017-11-25 246 views
0

我用两个CAShapeLayer's做了一个简单的进度线。动画正常工作,但从未调用CAAnimationDelegateanimationDidStartanimationDidStopCAAnimationDelegate代表永远不会被调用

这里是我的代码:

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

有谁知道为什么这些代表们从来没有叫什么名字?

+0

您是否曾将动画添加到“CALayer”? – nathan

+0

'topProgressBar.animation(forKey:“animate”)'应该是'topProgressBar.add(animation,forKey:“animate”)'? – nathan

+0

我不会添加它。我是不是该 ?因为对我来说这段代码有效。但是现在我想看看动画什么时候开始和结束,这部分不起作用。 – Kobe

回答

1

编辑:下面添加

要调用topProgressBar每个评论链接正确的解决方案。 animation(forKey: "animate")其中实际返回动画;它不启动它。您应该致电layer.add(animation, forKey:)而不是

+0

我尝试这样做,仍然不起作用 – Kobe

+0

显然,我必须将动画添加到CAShapeLayer,那么这就是所谓的 – Kobe

+0

是我在看我的代码,你必须调用layer.add(动画,forKey :)而不是你调用topProgressBar.animation(forKey:“动画”),它实际返回的动画;它不启动它 –

相关问题