我们知道,修改自定义创建的layer的部分属性时,会有动画的效果。但是修改view 的属性时,却没有动画出现,这是为什么呢?
Core Animation implements its implicit animation behaviors for layers using action objects. An action object is an object that conforms to the
CAAction
protocol and defines some relevant behavior to perform on a layer. AllCAAnimation
objects implement the protocol, and it is these objects that are usually assigned to be executed whenever a layer property changes.Animating properties is one type of action but you can define actions with almost any behavior you want. To do that, though, you have to define your action objects and associate them with your app’s layer objects.
CoreAnimation通过使用action对象来实现layer层的隐式动画。
@protocol CAAction
- (void)runActionForKey:(NSString *)event object:(id)anObject
arguments:(nullable NSDictionary *)dict;
@end
action是实现了CAAction协议,定义了layer层相关动画的对象。所有的CAAnimation对象都实现了这个协议,当layer的属性改变时,action对象会被分配关联到layer上,其动画方法被调用。
我们可以自定义action对象并关联在相应的layer上实现想要的任何效果。
Before an action can be performed, the layer needs to find the corresponding action object to execute. The key for layer-related actions is either the name of the property being modified or a special string that identifies the action. When an appropriate event occurs on the layer, the layer calls its
actionForKey:
method to search for the action object associated with the key. Your app can interpose itself at several points during this search and provide a relevant action object for that key.
开始展示动画之前,layer需要找到合适的action对象。
layer通过key去查找合适的action对象,可以用这个key返回一个action对象给layer,key是将要修改的属性名或指定的action的名字。查找流程式怎样的呢?
来到CALayer类中查看一些方法:
///* Returns the action object associated with the event named by the
// * string 'event'. The default implementation searches for an action
//* object in the following places:
// *
// * 1. if defined, call the delegate method -actionForLayer:forKey:
// * 2. look in the layer's `actions' dictionary
// * 3. look in any `actions' dictionaries in the `style' hierarchy
// * 4. call +defaultActionForKey: on the layer's class
// *
// * If any of these steps results in a non-nil action object, the
// * following steps are ignored. If the final result is an instance of
// * NSNull, it is converted to `nil'. */
- (nullable id<CAAction>)actionForKey:(NSString *)event;
///* Returns the default action object associated with the event named by
// * the string 'event'. The default implementation returns a suitable
//* animation object for events posted by animatable properties, nil
// * otherwise. */
+ (nullable id<CAAction>)defaultActionForKey:(NSString *)event;
///* Attach an animation object to the l