首页 > 解决方案 > 为什么我不能在 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 子类。但为什么需要这样做?

我不明白为什么默认背景层也不应该这样做。我在这里想念什么?

标签: ioscore-animationuiviewanimation

解决方案


推荐阅读