I'm wondering where the callbacks are (or if there are anything) for animations in a CALayer. Specifically, for implied animations like altering the frame, position, etc. In a UIView, you could do something like this:
[UIView beginAnimations:@"SlideOut" context:nil];
[UIView setAnimationDuration:.3];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animateOut:finished:context:)];
CGRect frame = self.frame;
frame.origin.y = 480;
self.frame = frame;
[UIView commitAnimations];
Specifically, the setAnimationDidStopSelector
is what I want for an animation in a CALayer. Is there anything like that?
TIA.
I answered my own question. You have to add an animation using
CABasicAnimation
like so:And implement the delegate method
animationDidStop:finished:
and you should be good to go. Thank goodness this functionality exists! :DJust a note for those who find this page on Google: You really can get the job done by setting the "delegate" property of your animation object to the object that will receive the notification and implementing the "animationDidStop" method in that object's .m file. I just tried it, and it works. I don't know why Joe Blow said that's not the correct way.
For 2018 ...
Swift 4.
use
.setCompletionBlock
In practice you need
[weak self]
or you'll typically crash.In the example, it just calls itself again.
Of course, you can call any function.
Note: if you're just getting started. It's worth remembering that
the "key" (as in
add#forKey
) is irrelevant and rarely used. Set it to nil. If for some reason you want to set it, set it to "any string" (say, your nickname). On the other hand...The
keyPath
in theCABasicAnimation
call is in fact the actual "thing you are animating", in other words it's literally a property of the layer (but just written as a string).In short
add#forKey
is almost always just nil, it is irrelevant.You often see code where these two are confused (thanks to the silly naming by apple), which causes all sorts of problems.
Do note that as of recently you can use
animationDidStop
with the delegate, see answer by @jack below! In some cases that is easier, sometimes it's easier to just use a completion block. If you have many different animes (which is often the case), just use completion blocks.If you don't want to mess around with
CATransaction
. I've created an extension that encapsulates the callback in the animation object.The code can be found in this snippet: https://gitlab.com/snippets/1786298
And you can then use it like this:
In Swift 4+ i have just added
delegate
asAnimation completion callback -
You can set the name of a given animation when setting up the CAAnimation object. In animationDiStop:finished, just compare the name of theAnimation object provided to perform you specific functionality based on the animation.