如何在 iOS swift 中在运行时更新 CAGradientLayer 颜色?

How to update CAGradientLayer colors on runtime in iOS swift?

我正在使用 UIView 扩展将渐变层应用到 UIView。我需要在滚动 tableview 时更改运行时的渐变颜色。我使用scrollview的contentoffset值来更新渐变颜色。

我试过的: 我试图从 superlayer 中删除该层并创建一个具有新颜色的新渐变层。但是应用程序出现内存问题并且 UI 有时会冻结。

是否可以在运行时更新 CAGradientLayer 渐变颜色?

extension UIView {
    func applyGradient(withColours colours: [UIColor], gradientOrientation orientation: GradientOrientation) {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = colours.map { [=12=].cgColor }
        gradient.startPoint = orientation.startPoint
        gradient.endPoint = orientation.endPoint
        self.layer.insertSublayer(gradient, at: 0)
    }
}

试试这个。希望对你有帮助..

let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
let gradient = CAGradientLayer()

gradient.frame = view.bounds
gradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor]

view.layer.insertSublayer(gradient, at: 0)

干杯

这个问题的答案是在同一范围内改变渐变层的颜色属性。我以前尝试过这样做,但是从另一个 scope.Now 它正在工作。下面给出答案。

Swift3.1代码:

let gradient = CAGradientLayer()

gradient.frame = view.bounds
gradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 1)
view.layer.insertSublayer(gradient, at: 0)

DispatchQueue.main.asyncAfter(deadline: .now() + 10) { 
// this will be called after 10 seconds.
    gradient.colors = [UIColor.red.cgColor, UIColor.black.cgColor]
}

另一种解决方案是使用动画块来更改渐变颜色...

extension CAGradientLayer
{
    func animateChanges(to colors: [UIColor],
                        duration: TimeInterval)
    {
        CATransaction.begin()
        CATransaction.setCompletionBlock({
            // Set to final colors when animation ends
            self.colors = colors.map{ [=10=].cgColor }
        })
        let animation = CABasicAnimation(keyPath: "colors")
        animation.duration = duration
        animation.toValue = colors.map{ [=10=].cgColor }
        animation.fillMode = kCAFillModeForwards
        animation.isRemovedOnCompletion = false
        add(animation, forKey: "changeColors")
        CATransaction.commit()
    }
}