Can I somehow have a block execute on every "tick" of a CAAnimation? It could possibly work like the code below. If there's a way to do this with a selector, that works too.
NSString* keyPath = @"position.x";
CGFloat endValue = 100;
[CATransaction setDisableActions:YES];
[self.layer setValue:@(toVal) forKeyPath:keyPath];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:keyPath];
animation.duration = 1;
animation.delegate = self;
__weak SelfClass* wself = self;
animation.eachTick = ^{
NSLog(@"Current x value: %f", [wself valueForKeyPath:keypath]);
};
[self.layer addAnimation:animation forKey:nil];
The typical technique is to employ a display link (
CADisplayLink
).So, define a property for the display link:
And then implement the methods to start, stop, and handle the display link:
Note, while a view is animating, you cannot look at its basic properties (because it will reflect the end destination rather than the "in flight" position), but rather you access the animated view's layer's
presentationLayer
, as shown above.Anyway, start the display link when you start your animation. And remove it upon completion.
With standard block-based animation, you'd do something like:
With Core Animation, it might look like:
Using a CADisplayLink to achieve this is ideal, but using it directly requires quite a bit of code.
Whether you're working at the Core Animation level or UIView animation level, take a look at the open source INTUAnimationEngine library. It provides a very simple API that is almost exactly like the UIView block-based API, but instead it runs the
animations
block each frame, passing in a percentage complete:If you simply call this method at the same time when you start your other animations and use the same duration & delay values, you'll be able to receive a callback at each frame of the animation. If you don't like duplicating code, INTUAnimationEngine can be used exclusively to run your animation as well, with advanced features like support for custom easing functions.