Search code examples
iosobjective-ccabasicanimationcaanimation

How to implement animationdidstop


Good Evening!

I have a peace of code but it is not calling the animationdidstop method. I could not identify why it does not work. I`ve tried many solutions..

-(IBAction)MakeCircle:(id)sender{

 // Add to parent layer
[self.view.layer addSublayer:circle];

// Configure animation
drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
drawAnimation.duration            = 5.0; 
drawAnimation.repeatCount         = 1.0;  
drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
drawAnimation.toValue   = [NSNumber numberWithFloat:1.0f];
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

// Add the animation
[circle addAnimation:drawAnimation forKey:@"drawCircleAnimation"];}


-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{

if(anim == [self.view.layer animationForKey:@"drawCircleAnimation"]){
    Label.text = [NSString stringWithFormat:@"Loser"];
}

}

Thanks!!


Solution

  • You are not setting yourself as the delegate of the animation. Add this line before adding the animation:

    drawAnimation.delegate = self;
    

    Edit:

    Oh. I know exactly what the problem is. The system copies your animation object when you submit the animation, so it won't be the same object in the completion routine. Try adding a unique key to the animation and checking that instead of checking to see if it's the same animation object you submitted.

    e.g.:

    drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    [drawAnimation setValue: @"mydrawCircleAnimation" forKey: @"animationKey"];
    //The rest of your animation code...
    

    Then in your animationDidStop:

    -(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
    {
      if([anim valueForKey: @"animationKey" 
        isEqualToString: @"mydrawCircleAnimation"])
      {
          Label.text = [NSString stringWithFormat:@"Loser"];
      }
    }
    

    Edit #2:

    There is an even cleaner way to handle animation completion code. You can attach a block to your animations and then write a general animationDidStop:completion: method that looks for the block and invokes it if found. See my answer in this thread:

    How to identify CAAnimation within the animationDidStop delegate?