Graphics Reference
In-Depth Information
[ self .colorLayer addAnimation :animation forKey : nil ];
}
- ( void )animationDidStop:( CABasicAnimation *)anim finished:( BOOL )flag
{
//set the backgroundColor property to match animation toValue
[ CATransaction begin ];
[ CATransaction setDisableActions : YES ];
self .colorLayer. backgroundColor = ( __bridge CGColorRef )anim. toValue ;
[ CATransaction commit ];
}
@end
The problem with CAAnimation using a delegate pattern instead of a completion block is
that it makes it quite awkward when you have multiple animations or animated layers to
keep track of. When creating animations in a view controller, you would usually use the
controller itself as the animation delegate (as we did in Listing 8.3), but since all the
animations will be calling the same delegate method, you need some way to determine
which completion call relates to which layer.
Consider the clock from Chapter 3, “Layer Geometry”; we originally implemented the
clock without animation by simply updating the angle of the hands every second. It would
look nicer if the hands animated to their new position realistically.
We can't animate the hands using implicit animation because the hands are represented by
UIView instances, and implicit animation is disabled for their backing layers. We could
animate them easily using UIView animation methods, but there is a benefit to using an
explicit property animation if we want more control over the animation timing (more on
this in Chapter 10). Animating those hands using CABasicAnimation is potentially quite
complex because we would need to detect which hand the animation relates to in the
-animationDidStop:finished: method (so we can set its finishing position).
The animation itself is passed as a parameter to the delegate method. You might be thinking
that you can store the animations as properties in the controller and compare them with the
parameter in the delegate method, but this won't work because the animation returned by
the delegate is an immutable copy of the original, not the same object.
When we attached the animations to our layers using -addAnimation:forKey: , there was a
key parameter that we've so far always set to nil . The key is an NSString that is used to
uniquely identify the animation if you later want to retrieve it using the layer's
-animationForKey: method. The keys for all animations currently attached to a layer can
be retrieved using the animationKeys property. If we were to use a unique key for each
animation, we could loop through the animation keys for each animated layer and compare
Search WWH ::




Custom Search