CAGradientLayer不适用于以编程方式创建的UI中的完整视图

问题描述

我正在处理一个iOS项目,该项目正在以编程方式创建其所有UI。不是情节提要。

我想在UIViewController的UIView的背景上添加渐变。

我创建了以下扩展方法

extension UIView {
    
    func addGradient(colors: [UIColor]) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.bounds = bounds
        gradientLayer.colors = colors.map { $0.cgColor }
        layer.insertSublayer(gradientLayer,at: 0)
    }
    
}

然后像这样将渐变添加到ViewController的viewDidLoad中。

let topColor = UIColor(red: 0.28,green: 0.521,blue: 0.696,alpha: 1)
let bottomColor = UIColor(red: 0.575,green: 0.615,blue: 0.692,alpha: 1)
view.addGradient(colors: [topColor,bottomColor])

但是渐变不会应用于屏幕的整个宽度和高度。

enter image description here

我打印了视图的边界,并显示了这些值。

(0.0,0.0,375.0,812.0)

所以我不确定为什么渐变仍不能覆盖整个视图。

解决方法

addGradient(colors:)方法中,设置gradientLayer's frame而不是bounds,即

func addGradient(colors: [UIColor]) {
    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = bounds //here.....

    //rest of the code...
}

此外,根据建议,将您的代码移至 viewDidLayoutSubviews() 方法,

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    let topColor = UIColor(red: 0.28,green: 0.521,blue: 0.696,alpha: 1)
    let bottomColor = UIColor(red: 0.575,green: 0.615,blue: 0.692,alpha: 1)
    view.addGradient(colors: [topColor,bottomColor])
}

这是因为gradient's frame每次在view's布局中进行任何更改时都必须更改。例如,纵向和横向。