我正在尝试创建一个子类CALayer
与定制index
我可以直接设置动画和更改属性,以便根据索引显示不同的图片。
在标题中,我声明:
@property NSUInteger index;
在实现中,我重写了needDisplayForKey
:
+ (BOOL)needsDisplayForKey:(NSString *)key
{
if ([key isEqualToString:@"index"])
return YES;
else
return [super needsDisplayForKey:key];
}
现在,在display
方法中,我想根据索引显示一张图片。然而,在动画过程中,self.index
永远不会改变,所以我必须查询表示层的值,与上的示例相反通过子类化提供 CALayer 内容 https://developer.apple.com/library/mac/#documentation/cocoa/conceptual/coreanimation_guide/Articles/ProvidingCALayerContent.html#//apple_ref/doc/uid/TP40006642-SW1:
- (void)display
{
NSUInteger presentationIndex = [(CustomLayer *)[self presentationLayer] index];
self.contents = (id)[[images objectAtIndex:presentationIndex] CGImage];
}
问题是,如果我这样做,我无法设置index
直接在动画之外的值,因为它只会更改模型层,并且display
方法显式查询表示层。
如果我添加一个复制值的初始化方法index
, 有用:
- (id)initWithLayer:(id)layer
{
self = [super initWithLayer:layer];
if (self) {
if ([layer isKindOfClass:[CustomLayer class]])
self.index = [(CustomLayer *)layer index];
}
return self;
}
然而,在动画之后或之前,总是存在 1 个图像故障,因为演示或模型值不匹配(取决于我是否设置index
是否达到目标值)。
- 令人惊讶的是,似乎
drawInContext:
方法总是有
正确的值[self index]
,但这不是我想要使用的方法,因为我刚刚设置了content
带有图像的属性。
- 根据我实现的方式,我会得到不同的行为
index
财产。如果我使用@dynamic index
(这是有效的,即使文档没有说自定义属性 getters/setters 将被动态实现),display
每次调用值index
被改变了。如果我使用@synthesize
或实现一个设置器,display
没有被调用,所以我需要改变content
在二传手中也是如此。
- 我应该使用实例变量吗?我应该使用动态实现吗?或者我应该使用
setValue:forKey:
反而?
正如您所看到的,我对如何获得我想要的结果以及如何使用自定义属性正确实现 CALayer 的子类有点困惑。任何帮助和解释,将不胜感激!