如何为图层shadowOpacity设置动画?

sud*_*-rf 41 iphone cocoa-touch objective-c quartz-graphics uiview

我有一个视图,我已将layerOpacity设置为1.

    theView.layer.shadowOpacity = 1.0;
Run Code Online (Sandbox Code Playgroud)

当视图在屏幕下方时,这看起来很好.当我将此视图移动到与另一个有阴影的视图齐平时,它们看起来不太好.有没有办法让shadowOpacity我的图层动画为0?我尝试使用动画块,但似乎这个属性不可动画.

替代文字

编辑:请求代码不起作用:

[UIView animateWithDuration:1.0 animations:^{
    splitView2.layer.shadowOpacity = 0;}
                 completion:NULL];
Run Code Online (Sandbox Code Playgroud)

小智 106

这将正常工作:

#import <QuartzCore/CAAnimation.h>

CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"shadowOpacity"];
anim.fromValue = [NSNumber numberWithFloat:1.0];
anim.toValue = [NSNumber numberWithFloat:0.0];
anim.duration = 1.0;
[vv.layer addAnimation:anim forKey:@"shadowOpacity"];
vv.layer.shadowOpacity = 0.0;
Run Code Online (Sandbox Code Playgroud)

对于Swift 3.0:

 let animation = CABasicAnimation(keyPath: "shadowOpacity")
 animation.fromValue = layer.shadowOpacity
 animation.toValue = 0.0
 animation.duration = 1.0
 view.layer.add(animation, forKey: animation.keyPath)
 view.layer.shadowOpacity = 0.0
Run Code Online (Sandbox Code Playgroud)

  • 如果你没有设置vv.layer.shadowOpacity = 0.0; 在最后一行,动画将完成,但之后它将跳回旧图层 (11认同)
  • 如果你想要阴影而不是关闭动画,这两个部分很重要:`anim.removedOnCompletion = NO; anim.fillMode = kCAFillModeForwards;` (2认同)

hei*_*iko 5

我将上面的代码放在 UIView 的一个小扩展中:

extension UIView {

func animateLayer<Value>(_ keyPath: WritableKeyPath<CALayer, Value>, to value:Value, duration: CFTimeInterval) {

    let keyString = NSExpression(forKeyPath: keyPath).keyPath
    let animation = CABasicAnimation(keyPath: keyString)
    animation.fromValue = self.layer[keyPath: keyPath]
    animation.toValue = value
    animation.duration = duration
    self.layer.add(animation, forKey: animation.keyPath)
    var thelayer = layer
    thelayer[keyPath: keyPath] = value
}
}
Run Code Online (Sandbox Code Playgroud)

用法如下:

animateLayer(\.shadowOffset, to: CGSize(width: 3, height: 3), duration:1)
animateLayer(\.shadowOpacity, to: 0.4, duration: 1)
Run Code Online (Sandbox Code Playgroud)

它没有经过彻底的测试。但为我工作。(也发布在这里