Graphics Reference
In-Depth Information
methods on
CATransaction
. Any view or layer properties you change between calls to
+beginAnimations:context:
and
+commitAnimations
will be animated
automatically because what those
UIView
animation methods are actually doing is setting
up a
CATransaction
.
In iOS 4, Apple added a new block-based animation method to
UIView
,
+animateWithDuration:animations:
. This is syntactically a bit cleaner than
having separate methods to begin and end a block of property animations, but really it's just
doing the same thing behind the scenes.
The
CATransaction
+
begin
and +
commit
methods are called internally by the
+animateWithDuration:animations:
method, with the body of the animations
block executed in between them so that any property changes that you make inside the
block will be encapsulated by the transaction. This has the benefit of avoiding any risk of
mismatched +
begin
and +
commit
calls due to developer error.
The
UIView
block-based animation allows you to supply a completion block to be called
when the animation has finished. This same feature is available when using the
CATransaction
interface by calling the
+setCompletionBlock:
method. Let's
adapt our example again so that it performs an action when the color change has completed.
We'll attach a completion block and use it to trigger a second animation that spins the layer
90 degrees each time the color has changed. Listing 7.3 shows the code, and Figure 7.2
shows the result.
Listing 7.3
Adding a Callback When the Color Animation Completes
- (
IBAction
)changeColor
{
//begin a new transaction
[
CATransaction
begin
];
//set the animation duration to 1 second
[
CATransaction
setAnimationDuration
:
1.0
];
//add the spin animation on completion
[
CATransaction
setCompletionBlock
:^{
//rotate the layer 90 degrees
CGAffineTransform
transform =
self
.
colorLayer
.
affineTransform
;
transform =
CGAffineTransformRotate
(transform,
M_PI_2
);
self
.
colorLayer
.
affineTransform
= transform;
}];