我通过这种方式为子类设置边框的宽度和颜色UIView
:
- (void) setViewBorder
{
self.layer.borderColor = [UIColor greenColor].CGColor;
self.layer.borderWidth = 3.0f;
}
我的问题是:如何制作动画?谢谢。
这两个borderColor
和borderWidth
是动画的属性,但因为你是在一个视图子类的UIView的动画块外这样,隐式动画(那些当你更改一个值,自动发生)被禁用。
如果要设置这些属性的动画,则可以使用进行显式动画处理CABasicAnimation
。由于要在同一层上设置两个属性的动画,因此可以将它们都添加到动画组中,并且只配置一次持续时间,时间等。请注意,显式动画纯粹是视觉上的,添加它们时模型值(实际属性)不会改变。这就是为什么你既要配置动画又要设置模型值的原因。
CABasicAnimation *color = [CABasicAnimation animationWithKeyPath:@"borderColor"];
// animate from red to blue border ...
color.fromValue = (id)[UIColor redColor].CGColor;
color.toValue = (id)[UIColor blueColor].CGColor;
// ... and change the model value
self.layer.borderColor = [UIColor blueColor].CGColor;
CABasicAnimation *width = [CABasicAnimation animationWithKeyPath:@"borderWidth"];
// animate from 2pt to 4pt wide border ...
width.fromValue = @2;
width.toValue = @4;
// ... and change the model value
self.layer.borderWidth = 4;
CAAnimationGroup *both = [CAAnimationGroup animation];
// animate both as a group with the duration of 0.5 seconds
both.duration = 0.5;
both.animations = @[color, width];
// optionally add other configuration (that applies to both animations)
both.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[self.layer addAnimation:both forKey:@"color and width"];
如果你在“设置插值值”部分下查看CABasicAnimation的文档,你会发现没有必要像我一样同时指定toValue和fromValue,因此可以将代码缩短一些。但是,为了清晰和易读(尤其是从Core Animation开始时),更加明确的做法可以帮助你(和你的同事)理解代码。
“由于您是在UIView动画块之外的视图子类中执行此操作,因此将禁用隐式动画(那些在更改值时自动发生的动画)。” 这在任何地方都有记录吗?我发现自己经常禁用层操作,对此一无所知。
@jrturton视图是层并返回的代表
NSNull
为actionForLayer:forKey:
当你是一个动画块外。整个过程在actionForKey:
有关CALayer的讨论中有所记录。我将看看是否可以为委托物找到更好的参考。@jrturton在
layer
UIView属性的文档中,您可以看到视图是委托,并且您不应该更改委托。@jrturton至于视图的实际作用
actionForLayer:forKey:
,最好的办法是在这里找到我的答案,然后依次引用该答案。但是,您可以进行自己的实验,actionForLayer:forKey:
并在动画块的内部和外部询问图层委托(或直接在视图中进行),然后查看返回的响应。我不记得曾经在某处看到过正式记录。@SwiftArchitect是的,以某种方式使人们长时间不被注意