init(colorLiteralRed:,green:,blue:,alpha:) 在 Swift 4 中弃用

init(colorLiteralRed:,green:,blue:,alpha:) deprecated in Swift 4

let startingColorOfGradient = UIColor(colorLiteralRed: 255/255, green: 
255/255, blue: 255/255, alpha: 1.0).cgColor
let endingColorOFGradient = UIColor(colorLiteralRed: 251/255, green: 
247/255, blue: 234/255, alpha: 1.0).cgColor
let gradient: CAGradientLayer = CAGradientLayer()

错误:

'init(colorLiteralRed:green:blue:alpha:)' was obsoleted in Swift 4.0 (Swift._ExpressibleByColorLiteral)

如果 init(colorLiteralRed:,green:,blue:,alpha:) 在 Swift 4 中被弃用,我该如何使用渐变颜色?

init(colorLiteralRed:green:blue:alpha:) 旨在与由开发工具管理的颜色文字一起使用。

为什么不用普通的init(red:green:blue:alpha:)

let startingColorOfGradient = UIColor(red: 255.0/255.0, green:
    255.0/255.0, blue: 255.0/255.0, alpha: 1.0).cgColor
let endingColorOFGradient = UIColor(red: 251.0/255.0, green:
    247.0/255.0, blue: 234.0/255.0, alpha: 1.0).cgColor
let gradient: CAGradientLayer = CAGradientLayer()

(像 234.0/255.0 这样的写法不是强制性的,在上面 Swift 的上下文中。但它会阻止 Swift 编译器将 234/255 解释为整数除法其他一些上下文。)

您可以简单地使用 UIColor class 的以下方法来实例化红色、绿色、蓝色、Alpha 的颜色。

注意:红色、绿色、蓝色和 Alpha 的值介于 0 到 1 之间。

let colorStart = UIColor(red:0.1 , green: 0.2, blue: 0.5, alpha: 1.0)
let colorEnd = UIColor(red:0.21 , green: 0.32, blue: 0.15, alpha: 1.0)

func createGradientLayer() {
     gradientLayer = CAGradientLayer()
     gradientLayer.frame = self.view.bounds
     gradientLayer.colors = [colorStart.CGColor, colorEnd.CGColor]
     self.view.layer.addSublayer(gradientLayer)
}

创建渐变图层可以参考

https://www.appcoda.com/cagradientlayer/

另一种方式:https://developer.apple.com/documentation/uikit/uicolor/1621925-init

init(displayP3Red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)

Initializes and returns a color object using the specified opacity and RGB component values in the Display P3 color space.

您可以使用 displayP3Red 而不是 colorLiteralRed

let startingColorOfGradient = UIColor(displayP3Red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0).cgColor
let endingColorOFGradient = UIColor(displayP3Red: 251/255, green: 247/255, blue: 234/255, alpha: 1.0).cgColor
let gradient: CAGradientLayer = CAGradientLayer()

你可以使用

UIColor(red: CGFloat(255.0), green: CGFloat(255.0), blue: CGFloat(255.0), alpha: CGFloat(255.0))