How to animate layer shadowOpacity?

后端 未结 4 1244
生来不讨喜
生来不讨喜 2021-01-30 10:35

I have a view on which I\'ve set the layerOpacity to 1.

    theView.layer.shadowOpacity = 1.0;

This looks fine when the view is farther down th

4条回答
  •  灰色年华
    2021-01-30 11:14

    I've put above code in a little extension of UIView:

    extension UIView {
    
    func animateLayer(_ keyPath: WritableKeyPath, 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
    }
    }
    

    Usage like:

    animateLayer(\.shadowOffset, to: CGSize(width: 3, height: 3), duration:1)
    animateLayer(\.shadowOpacity, to: 0.4, duration: 1)
    

    It's not thoroughly tested. but worked for me. (Also posted here)

提交回复
热议问题