作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我正在处理的 CALayer 子类中,我有一个要自动设置动画的自定义属性,也就是说,假设该属性称为“myProperty”,我需要以下代码:
[myLayer setMyProperty:newValue];
@interface ERAnimatablePropertyLayer : CALayer {
float myProperty;
}
@property (nonatomic, assign) float myProperty;
@end
@implementation ERAnimatablePropertyLayer
@dynamic myProperty;
- (void)drawInContext:(CGContextRef)ctx {
... some custom drawing code based on "myProperty"
}
- (id <CAAction>)actionForKey:(NSString *)key {
if ([key isEqualToString:@"myProperty"]) {
CABasicAnimation *theAnimation = [CABasicAnimation animationWithKeyPath:key];
theAnimation.fromValue = [[self presentationLayer] valueForKey:key];
... I want to do something special here, depending on both from and to values...
return theAnimation;
}
return [super actionForKey:key];
}
+ (BOOL)needsDisplayForKey:(NSString *)key {
if ([key isEqualToString:@"myProperty"])
return YES;
return [super needsDisplayForKey:key];
}
@end
最佳答案
您需要避免为要设置动画的属性使用自定义 getter 和 setter。
覆盖 didChangeValueForKey:
方法。使用它来设置要设置动画的属性的模型值。
不要在 Action 动画上设置 toValue。
@interface MyLayer: CALayer
@property ( nonatomic ) NSUInteger state;
@end
@implementation MyLayer
@dynamic state;
- (id<CAAction>)actionForKey: (NSString *)key {
if( [key isEqualToString: @"state"] )
{
CABasicAnimation * bgAnimation = [CABasicAnimation animationWithKeyPath: @"backgroundColor"];
bgAnimation.fromValue = [self.presentationLayer backgroundColor];
bgAnimation.duration = 0.4;
return bgAnimation;
}
return [super actionForKey: key];
}
- (void)didChangeValueForKey: (NSString *)key {
if( [key isEqualToString: @"state"] )
{
const NSUInteger state = [self valueForKey: key];
UIColor * newBackgroundColor;
switch (state)
{
case 0:
newBackgroundColor = [UIColor redColor];
break;
case 1:
newBackgroundColor = [UIColor blueColor];
break;
case 2:
newBackgroundColor = [UIColor greenColor];
break;
default:
newBackgroundColor = [UIColor purpleColor];
}
self.backgroundColor = newBackgroundColor.CGColor;
}
[super didChangeValueForKey: key];
}
@end
关于core-animation - 带有 actionForKey : how do I get the new value for the property? 的自定义属性动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10298905/
我是一名优秀的程序员,十分优秀!