CAAnimation with callback on step

552 Views Asked by At

I have a CAAnimation that uses a timing function. I need callbacks to happen consistently thought the animation. Similar to jQuery's step callback. I have scoured the internet for a solution to this but have not been able to find one. (maybe I am not searching correctly)

My code thus far:

CABasicAnimation *rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat:rotation / 180.0 * M_PI];
rotationAnimation.duration = duration;
rotationAnimation.repeatCount = 0;
rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];

[_image.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];

I know the delegate has these two methods:

– animationDidStart:
– animationDidStop:finished:

It would be nice if there was a way to create a category to implement an

- animationProgress:

Or something similar. Or maybe CAAnimations aren't the solution.

How can I achieve this with CAAnimations or any alternative?

2

There are 2 best solutions below

0
On

You might want to use

UIView's animateWithDuration:delay:options:animations:completion:

An easy way to set this up would then be

- (void)animateStuff {
 [UIView animateWithDuration:duration
                       delay:delay
                     options:UIViewAnimationOptionTransitionNone
                  animations:^{ // custom animations }
                  completion:^(BOOL finished) {
                       // check if you want to continue with
                       if (<check to continue>) {
                           [self animateStuff];
                       }
                  }];
}

This serves well if you can break up your entire animation into small fragments. Using the above code you can then animate each of the smaller fragment and continue doing so until the entire animation is done.

0
On
    CABasicAnimation *basicAnimation=[CABasicAnimation animationWithKeyPath:<AnimatableProperty>];
    CALayer *layerToAnimate=[CALayer layer];

    [CATransaction begin];
    [CATransaction setCompletionBlock:^{
       //Stuff to be done on completion
    }];
    [layerToAnimate addAnimation:basicAnimation forKey:@"myCustomAnimation"];
    [CATransaction commit];