Search code examples
ioscore-animationobjective-c-blocks

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 code block that describes what the view properties will end up looking after the animation is finished.

How does this work?

I could understand (I think) if this was done using some declarative format, but from the looks of it, the animation block is just a regular piece of code that presumably has to be executed, the results inspected and then someone transcoded into the actual lower-level graphics code that performs the animation.

Is the block actually executed (or somehow reverse-engineered) and if so, when?

If this code is executed before the animation starts, then how come the changes to the referenced view properties are not reflected immediately?

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


Solution

  • Yes, the block is actually invoked -- then it changes the view's properties immediately. The UIView's property setters are responsible to see if the set was used within an animation context -- if so, they calculate the animation frames etc. using CoreAnimation and CoreGraphics.

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