ios - 为什么我不能在 UIView 默认背景层上为自定义属性设置动画?
问题描述
我想为 UIView 默认背景层设置动画。在viewDidLoad
我添加我的自定义属性以动画到视图中:
self.layer.delegate = self;
[self.layer setValue:0 forKey:@"value"];
如此处所述。
要更改的值的 setter 方法如下所示,并更新背景层上添加的自定义属性:
- (void)setValue:(NSInteger)value
{
_value = value;
[self.layer setValue:[NSNumber numberWithInteger:value] forKey:@"value"];
[self setNeedsDisplay];
}
并且在actionForLayer:forKey:
我看来,我正在返回一个动画,如此处所述,它应该从当前值动画到新的设置值,如下所示:
- (id<CAAction>)actionForLayer:(CALayer*)layer forKey:(NSString*)key
{
if([key isEqualToString:@"value"])
{
CAAnimation* action = (CAAnimation*)[self actionForLayer:layer forKey:@"backgroundColor"];
if(action != (CAAnimation*)[NSNull null])
{
CABasicAnimation* animation = [CABasicAnimation animation];
animation.keyPath = @"value";
animation.fromValue = [self.layer valueForKey:@"value"];
animation.toValue = [NSNumber numberWithInteger:_value];
animation.beginTime = action.beginTime;
animation.duration = action.duration;
animation.speed = action.speed;
animation.timeOffset = action.timeOffset;
animation.repeatCount = action.repeatCount;
animation.repeatDuration = action.repeatDuration;
animation.autoreverses = action.autoreverses;
animation.fillMode = action.fillMode;
animation.timingFunction = action.timingFunction;
animation.delegate = action.delegate;
[self.layer addAnimation:animation forKey:@"value"];
}
}
return [super actionForLayer:layer forKey:key];
}
我像这样绘制我的视图内容:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
[self drawARainbowUnicorn:context];;
}
从我的视图控制器我做一个块动画是这样的:
[UIView animateWithDuration:10.0 animations:
^{
self->_myView.value = self->_myView.maximumValue;
}];
我看到的是该值始终在最终位置上显示为动画。我期望的是该值会在给定时间内动画到该位置。
我发现的所有示例都添加了一个单独的层来像这样
或这样
或这样的动画,我知道这个 StackOverflow问题和我发现的其他一些问题。
我还查看了 Apple 的这个较旧的示例项目。他们还创建了一个 CALayer 子类。但为什么需要这样做?
我不明白为什么默认背景层也不应该这样做。我在这里想念什么?
解决方案
推荐阅读
- c++ - C++11统一初始化:初始化列表和多参数构造函数之间的歧义?
- css - 我如何让这个 flexbox 容器响应较小的屏幕尺寸?
- reactjs - 需要在无状态函数中添加 ComponentDidMount
- android - Android Studio、React Native、Gradle:项目有时会构建但由于不明确的错误和警告而无法运行
- python - 模块的可调/可配置
- git - Git:只有一些未修改但已删除的文件是合并冲突。为什么?
- elasticsearch - 弹性 - 批量上传:索引 x 更新
- r - R Markdown 错误:临时文件中的错误(pattern = “_rs_rdf_”,tmpdir = outputFolder,fileext = “.rdf”):临时名称太长
- rust - 无法使异步闭包与 Warp::Filter 一起使用
- android - MediaPlayer 只播放某些 WAV 文件