Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

uicolor

swift4

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()

Error:

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

How do I use gradient color if init(colorLiteralRed:,green:,blue:,alpha:) is deprecated in Swift 4?

like image 307
Zeus Eternal Avatar asked Jul 27 '17 21:07

Zeus Eternal


3 Answers

init(colorLiteralRed:green:blue:alpha:) is intended to be used with Color Literals which are managed by development tools.

Why don't you use normal 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()

(Writing like 234.0/255.0 is not mandatory, in the context as above in Swift. But it prevents Swift compiler to interpret 234/255 as an integer division in some other contexts.)

like image 161
OOPer Avatar answered Nov 12 '22 15:11

OOPer


You can simply use below method of UIColor class to instantiate color from Red, Green, Blue, Alpha.

Note: Red, Green, Blue, and Alpha have a value ranging from 0 to 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)
}

To create gradient layer you can take reference from

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

like image 37
Sudhir kumar Avatar answered Nov 12 '22 14:11

Sudhir kumar


Another way : 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.

you can use displayP3Red instead of 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()
like image 2
Vini App Avatar answered Nov 12 '22 16:11

Vini App