Quantcast
Channel:
Viewing all articles
Browse latest Browse all 27

CAAnimation delegate not working (Swift)

$
0
0

CAAnimation provides a way of receiving a callback upon start or completion of an animation.
If you have a ‘pure’ class, that is a class that does not inherit from anything, doing this will have no effect:


class Petal { func startAnimation(duration: Double = 2.0) { let pathAnimation = CABasicAnimation(keyPath: "strokeEnd"); pathAnimation!.delegate = self; pathAnimation!.duration = duration; pathAnimation!.fromValue = 0.0; pathAnimation!.toValue = 1.0; self.shapeLayer.addAnimation(pathAnimation!, forKey: "strokeEnd"); } func animationDidStart(anim: CAAnimation) { Swift.print("ANIMATION DID START!"); } func animationDidStop(anim: CAAnimation, finished flag: Bool) { Swift.print("ANIMATION DID END!"); } }

The reason is because:
You must subclass NSObject, as the delegate methods exist as an informal protocol extension on NSObject

So simply changing it to this is enough:


class Petal:NSObject { // Subclass NSObject func startAnimation(duration: Double = 2.0) { .... } // These are now overrides override func animationDidStart(anim: CAAnimation) { Swift.print("ANIMATION DID START!"); } override func animationDidStop(anim: CAAnimation, finished flag: Bool) { Swift.print("ANIMATION DID END!"); } }

Viewing all articles
Browse latest Browse all 27

Trending Articles