Uiview CAGradientLayer未显示(Swift 3)

Uiview CAGradientLayer未显示(Swift 3),uiview,swift3,gradient,Uiview,Swift3,Gradient,我正在制作一个天气应用程序,为了显示一天中的最高和最低温度,我使用了一个UIView,它是我使用.layer.cornerRadius取整的角。现在我想添加一个渐变层,用不同的颜色表示温度,但是渐变层没有出现。这是我的viewDidLoad,视图名称为currentMinMaxTemperatureView: let gradientLayer = CAGradientLayer() gradientLayer.frame = currentMinMaxTemperatureView.b

我正在制作一个天气应用程序,为了显示一天中的最高和最低温度,我使用了一个UIView,它是我使用.layer.cornerRadius取整的角。现在我想添加一个渐变层,用不同的颜色表示温度,但是渐变层没有出现。这是我的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)
为什么它没有出现?运行此操作时,我的视图如下所示:

试试下面的方法

gradientLayer.colors = [UIColor.blue.cgColour, UIColor.yellow.cgColour, UIColor.red.cgColour]
试试下面的方法

gradientLayer.colors = [UIColor.blue.cgColour, UIColor.yellow.cgColour, UIColor.red.cgColour]

您的代码有几个问题:

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

只需按以下方式转换颜色:

[UIColor.blue.cgColor, UIColor.yellow.cgColor, UIColor.red.cgColor]
其次,要确保在将currentMinMaxTemperatureView添加到superview后添加渐变。否则,其边界将为零


稍后在UIViewController生命周期中尝试添加渐变,如ViewDidLayoutSubviews

您的代码有几个问题:

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

只需按以下方式转换颜色:

[UIColor.blue.cgColor, UIColor.yellow.cgColor, UIColor.red.cgColor]
其次,要确保在将currentMinMaxTemperatureView添加到superview后添加渐变。否则,其边界将为零


稍后在UIViewController生命周期中尝试添加渐变,如ViewDidLayoutSubviews

感谢您提供的关于边界的提示!谢谢你关于边界的提示!