@@ -7,18 +7,28 @@ fileprivate protocol AnimationLooperDelegate: class {
77}
88
99fileprivate class TurtleAnimator : NSObject , CAAnimationDelegate {
10+ var turtleLayer : CALayer = {
11+ let layer = CATextLayer ( )
12+ layer. bounds = CGRect ( x: 0 , y: 0 , width: 50 , height: 50 )
13+ layer. string = " 🐢 "
14+ return layer
15+ } ( )
16+
1017 var layers : [ CAShapeLayer ]
1118 var index = 0
19+ var showTurtle : Bool
1220 weak var delegate : AnimationLooperDelegate ?
1321
1422 deinit {
23+ turtleLayer. removeFromSuperlayer ( )
1524 self . layers. forEach { layer in
1625 layer. removeAllAnimations ( )
1726 }
1827 }
1928
20- init ( _ layers: [ CAShapeLayer ] ) {
29+ init ( _ layers: [ CAShapeLayer ] , showTurtle : Bool = false ) {
2130 self . layers = layers
31+ self . showTurtle = showTurtle
2232 super. init ( )
2333 if self . layers. count > 0 {
2434 self . scheduleAnimation ( layers [ index] )
@@ -29,20 +39,39 @@ fileprivate class TurtleAnimator: NSObject, CAAnimationDelegate {
2939
3040 public func animationDidStop( _ anim: CAAnimation , finished flag: Bool ) {
3141 layers [ index] . removeAllAnimations ( )
42+ turtleLayer. removeAllAnimations ( )
43+ CATransaction . begin ( )
44+ CATransaction . disableActions ( )
45+ turtleLayer. removeFromSuperlayer ( )
46+ CATransaction . commit ( )
47+
3248 if index < layers. count - 1 {
3349 index += 1
3450 scheduleAnimation ( layers [ index] )
3551 }
3652 }
3753
3854 func scheduleAnimation( _ layer: CAShapeLayer ) {
55+ let duration = 3.0 / Double( layers. count)
3956 let animation = CABasicAnimation ( keyPath: " strokeEnd " )
4057 animation. fromValue = 0.0
4158 animation. toValue = 1.0
4259 animation. delegate = self
43- animation. duration = 3.0 / Double ( layers . count )
60+ animation. duration = duration
4461 layer. strokeEnd = 1.0
4562 layer. add ( animation, forKey: nil )
63+
64+ if showTurtle {
65+ CATransaction . begin ( )
66+ CATransaction . disableActions ( )
67+ layer. addSublayer ( turtleLayer)
68+ CATransaction . commit ( )
69+
70+ let movingAnimation = CAKeyframeAnimation ( keyPath: " position " )
71+ movingAnimation. path = layer. path
72+ movingAnimation. duration = duration
73+ turtleLayer. add ( movingAnimation, forKey: nil )
74+ }
4675 }
4776}
4877
@@ -120,15 +149,15 @@ public class AnimatedTurtleView: UIView, AnimationLooperDelegate {
120149
121150 private var animator : TurtleAnimator ?
122151
123- public func animate( ) {
152+ public func animate( showTurtle : Bool = false ) {
124153 CATransaction . begin ( )
125154 CATransaction . disableActions ( )
126155 self . shapeLayers. forEach { layer in
127156 layer. removeAllAnimations ( )
128157 layer. strokeEnd = 0
129158 }
130159 CATransaction . commit ( )
131- self . animator = TurtleAnimator ( self . shapeLayers)
160+ self . animator = TurtleAnimator ( self . shapeLayers, showTurtle : showTurtle )
132161 }
133162
134163 fileprivate func turtleAnimatorDidEnd( _ animationLooper: TurtleAnimator ) {
0 commit comments