gpt4 book ai didi

core-animation - 带有 actionForKey : how do I get the new value for the property? 的自定义属性动画

转载 作者:行者123 更新时间:2023-12-04 04:27:04 26 4
gpt4 key购买 nike

在我正在处理的 CALayer 子类中,我有一个要自动设置动画的自定义属性,也就是说,假设该属性称为“myProperty”,我需要以下代码:

[myLayer setMyProperty:newValue];

导致从当前值到“newValue”的平滑动画。

使用覆盖 actionForKey: 和 needsDisplayForKey: 的方法(见下面的代码)我能够让它运行得非常好,只需在旧值和新值之间进行插值。

我的问题是我想根据属性的当前值和新值使用稍微不同的动画持续时间或路径(或其他),但我无法弄清楚如何从 actionForKey 中获取新值:

提前致谢
@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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com