CAGradientLayer 不出现(Swift 3)

Car*_*tti 1 gradient uiview swift3

我正在制作一个天气应用程序,为了显示当天的最高和最低温度,我使用了一个 UIView,它是我使用 .layer.cornerRadius 圆角的角落。现在我想添加一个具有不同颜色(象征温度)的渐变层,但没有出现gradientLayer。这是我的 viewDidLoad(),视图名称是 currentMinMaxTemperatureView:

let gradientLayer = CAGradientLayer()
    gradientLayer.frame = currentMinMaxTemperatureView.bounds
    gradientLayer.cornerRadius = currentMinMaxTemperatureView.cornerRadius
    gradientLayer.colors = [UIColor.blue, UIColor.yellow, UIColor.red]
    currentMinMaxTemperatureView.layer.addSublayer(gradientLayer)
Run Code Online (Sandbox Code Playgroud)

为什么不出现?运行此程序时,我的视图如下所示:

在此处输入图片说明

KLD*_*KLD 5

您的代码有几个问题:

首先,正如@archLucifer 提到的,CAGradientLayer期望CGColor,而不是UIColor

只需像这样转换您的颜色:

[UIColor.blue.cgColor, UIColor.yellow.cgColor, UIColor.red.cgColor]
Run Code Online (Sandbox Code Playgroud)

其次,你要确保你添加渐变后,currentMinMaxTemperatureView加入到上海华。否则,bounds它将是nil.

尝试在UIViewController生命周期的后期添加渐变,例如ViewDidLayoutSubviews()