How do iOS animation blocks work?

In iOS, you can animate view objects using animation blocks:

[UIView animateWithDuration:1.0 animations:^{ firstView.alpha = 0.0; secondView.alpha = 1.0; }]; 

What we have here is a block of code that describes how the properties of the view will look after the animation is completed.

How it works?

I could understand (I think) if this was done using some declarative format, but from his point of view, the animation block is just an ordinary piece of code that is supposed to be executed, the results are checked, and then someone is transcoded into the actual lower level graphics code that performs the animation.

Is the block actually executed (or somehow reconstructed), and if so, when?

If this code is executed before the start of the animation, then how does the immediate reflection of changes in the properties of the reference view occur?

What happens if I put the code in a block that does not change the properties of the view, but does something else?

+8
ios core-animation objective-c-blocks
source share
3 answers

Yes, the block is actually called - it immediately changes the properties of the view. UIView property installers are responsible for determining whether this set was used in the context of the animation — if so, they calculate animation frames, etc., using CoreAnimation and CoreGraphics.

If you put code without animation in these blocks, nothing special will happen - the block will be executed immediately.

+8
source share

It is instructive to look at the equivalent code before the blocks:

 [UIView beginAnimations:@"foo" context:NULL]; [UIView setAnimationDuration:1.0]; firstView.alpha = 0.0; secondView.alpha = 1.0; [UIView commitAnimations]; 

So you see that even before blocks, change properties are also set directly; however, they do not take effect immediately (they are animated).

How it works? Presumably, when you set a property in a view, it checks to see if you are beginAnimations , but not commitAnimations , and does not take effect immediately if there is one (but rather adds it to the list of things to animate for this animation).

So what makes the block version very simple in the context of the pre-blocks version: you can just think of it as starting an animation block inside the beginAnimations and commitAnimations .

+6
source share

Apple doesn't really talk about the details about how this works, but here's what I think:

The system adds KVO watchers to all the animation properties of the view when the view is added to the view hierarchy.

When your animation block executes, the system sets a state that monitors KVO notifications about these properties. Then, the code that is called creates and adds the appropriate CAAnimation objects to each affected view layer.

+1
source share

All Articles