最近在做CALayer自定义属性(@property
修饰)动画。之前没有深究过,现在有很多有意思的发现,写出来分享给大家。
首先把Demo LNLoadingLayer分享给大家,这是一个loading动画。
在做CALayer自定义属性动画之前,要先了解一个概念,即CALayer是一个符合键值编码的容器类(Key-Value Coding Compliant Container Classes)
。
符合键值编码的容器类
CALayer和CAAnimation都是符合键值编码的容器类(Key-Value Coding Compliant Container Classes),
这意味着你可以用任意key
来设置值,即使这个key
没有声明为CALayer的property。
以下是苹果Core Animation 编程指南的介绍:
TheCAAnimationandCALayer classes are key-value coding compliant container classes, which means that you can set values for arbitrary keys. Even if the key
someKey
is not a declared property of theCALayer
class, you can still set a value for it as follows:[ theLayer setValue:[NSNumber numberWithInteger:50] forKey:@“someKey”];
You can also retrieve the value for arbitrary keys like you would retrieve the value for other key paths. For example, to retrieve the value of the
someKey
path set previously, you would use the following code:someKeyValue = [theLayer valueForKey:@“someKey”];
因此,在CALayer中,用@dynamic修饰的属性,即使没有实现setter getter也不会崩溃。
@interface DynamicTest : CALayer
@property NSString *title;
@end
@implementation DynamicTest
@dynamic title;
@end
DynamicTest *test = [[DynamicTest alloc] init];
test.title = @"title";//正常工作,不会崩溃。
//另外,CALayer和CAAnimation,会自动为@dynamic修饰的属性添加NSCoding协议的支持。不用@dynamic修饰,则不支持。
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:test];
DynamicTest *unarchiveTest = [NSKeye