以下代码是CALayer
的子类。如果我致电animateVal
,则drawInContext
会动画。那很棒。
我试图将其转换为actionForKey
的隐式动画。如果我为val
属性(layer.val = 10
)分配了值,则会立即更改val
,并使用相同的值drawInContext
重复调用val
,一个我刚刚分配的,一遍又一遍。
我做错了什么?
@interface MyLayer : CALayer
@property (nonatomic, assign) CGFloat val;
- (void)animateVal:(CGFloat)val;
@end
@implementation MyLayer
@dynamic val;
+ (BOOL)needsDisplayForKey:(NSString *)key {
return [key isEqualToString:@"val"] || [super needsDisplayForKey:key];
}
- (id<CAAction>)actionForKey:(NSString *)event {
if ([event isEqualToString:@"val"]) {
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"val"];
anim.duration = 3.0;
return anim;
}
return [super actionForKey:event];
}
- (void)animateVal:(CGFloat)val {
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"val"];
anim.toValue = [NSNumber numberWithFloat:val];
anim.duration = 3.0;
[self addAnimation:anim forKey:nil];
}
- (void)drawInContext:(CGContextRef)ctx {
CGContextAddRect(ctx, CGRectMake(10, 10, self.val, self.val));
CGContextSetFillColorWithColor(ctx, [UIColor greenColor].CGColor);
CGContextFillPath(ctx);
}
@end
答案 0 :(得分:1)
哎呀。
解决方案是在返回操作时设置 fromValue 。
anim.fromValue = [[self presentationLayer] valueForKey:event];