title: CAAnimation to animate a checkmark drawing
body: <p>I am trying to make a simple check mark control, which consists of just a square and a checkmark in it. I would like to animate drawing and erasing of the check mark when the control is tapped. This is what I have so far:</p>
  
  <pre><code>let path = UIBezierPath()
  path.move(to: CGPoint(x: 0, y: checkBox.size * 2 / 3))
  path.addLine(to: CGPoint(x: checkBox.size / 3, y: checkBox.size))
  path.addLine(to: CGPoint(x: checkBox.size, y: 0))
  
  pathLayer.frame = checkBox.bounds
  pathLayer.path = path.cgPath
  pathLayer.strokeColor = UIColor.red().cgColor
  pathLayer.fillColor = nil
  pathLayer.lineWidth = checkMarkWidth
  pathLayer.lineJoin = kCALineJoinBevel
  
  let pathAnimation = CABasicAnimation(keyPath:"strokeEnd")
  pathAnimation.duration = checkMarkAnimationDuration
  pathAnimation.fromValue = NSNumber(floatLiteral: 0)
  pathAnimation.toValue = NSNumber(floatLiteral: 1)
  
  let reverseAnimation = CABasicAnimation(keyPath:"strokeEnd")
  reverseAnimation.duration = checkMarkAnimationDuration
  reverseAnimation.fromValue = NSNumber(floatLiteral: 1)
  reverseAnimation.toValue = NSNumber(floatLiteral: 0)
  reverseAnimation.delegate = self
  </code></pre>
  
  <p>Then I start the animations like this:</p>
  
  <pre><code>var on: Bool = false {
      didSet {
          if on {
              checkBox.layer.addSublayer(pathLayer)
              pathLayer.removeAllAnimations()
              pathLayer.add(pathAnimation, forKey:"strokeEnd")
          } else {
              pathLayer.removeAllAnimations()
              pathLayer.add(reverseAnimation, forKey:"strokeEnd")
          }
      }
  }
  </code></pre>
  
  <p>Finally in my CAAnimationDelegate I do this:</p>
  
  <pre><code>public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
      pathLayer.removeFromSuperlayer()
  }
  </code></pre>
  
  <p>This looks good, except that when I test it on the real device there is a little flash when the reversed animation is done, but before the layer is removed. It seems I am missing an <code>animationWillStop</code> callback.</p>
  
  <p><a href="https://i.stack.imgur.com/t457Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t457Z.png" alt="enter image description here"></a></p>
  
  <p>Any ideas how to fix this glitch?</p>
  
  <p>Also any other suggestions on how to improve this code are welcome, cause I'm completely new to Core Animation.</p>