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

标签 ios swift animation uiview cagradientlayer

我正在使用 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 { $0.cgColor }
        gradient.startPoint = orientation.startPoint
        gradient.endPoint = orientation.endPoint
        self.layer.insertSublayer(gradient, at: 0)
    }
}

最佳答案

这个问题的答案是在同一个范围内改变渐变图层的颜色属性。我以前尝试过这样做,但是从不同的范围开始。现在它正在工作。答案如下。

Swift 3.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]
}

关于ios - 如何在 iOS swift 运行时更新 CAGradientLayer 颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44156241/

相关文章:

iphone - presentationLayer 值在动画期间未更新?

ios - SKPaymentTransaction 的 originalTransaction.transactionReceipt nil 用于恢复非消耗品

ios - 如何在某些生命周期事件之前/之后初始化 ViewController 的安全属性?

ios - 将 UIView 从矩形动画为梯形

java - 沿着具有附加要求的路径制作动画

ios - 选择其他文本字段时如何重置 UIPickerView 内的值?

ios - 在沙盒模式下检查应用内购买自动续订订阅

ios - 在 iPhone X 上测试时应用程序崩溃,但模拟器运行正常, "EXC_BAD_ACCESS"是什么

ios - (Swift 2) 如何在我的数据库中获取一个随机的 Realm 对象?

iphone - 用动画翻页(UIWebView)