Matt Matt - 5 months ago 27
iOS Question

Swift 2.0 understanding how animation with duration works in animation closure

is easy to use:

UIView.animateWithDuration(1.0) {
self.someView.alpha = 1.0

How does the function update the variables in the closure to animate instead of just jumping in this case to
alpha = 1.0
on the first iteration?


This works because of the special design of CALayer. Every CALayer has two conceptual layers, both exposed as properties. There is the modelLayer which is what you access and modify through properties like someView.alpha and generally holds the state of the layer. The model layer updates immediately when you modify related properties, whether or not you're inside a UIView animation block. Then there is also the presentationLayer which is actually what gets rendered by the system. The presentation layer usually mirrors the model layer, except when animating. I don't know the specifics, but UIView.animateWithDuration does something to tell CoreAnimation, "when I run this animation block, record the changes in the model layer (diff before and after), and then apply them incrementally to the presentation layer over the given duration".

This is why someView.alpha is immediately updated despite the animation not having finished, because your code interacts with the model layer. If you access the presentation layer, you will see that the updated value is applied incrementally.