36
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?

0mpurdy
  • 3,198
  • 1
  • 19
  • 28
Zeus Eternal
  • 427
  • 1
  • 4
  • 11

4 Answers4

55

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

OOPer
  • 47,149
  • 6
  • 107
  • 142
  • There are two new methods in UIColor that accepts integer values from 0 to 255. See my answer here: https://stackoverflow.com/a/58124535/2631081 – Blip Sep 26 '19 at 20:49
4

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/

pkamb
  • 33,281
  • 23
  • 160
  • 191
Sudhir kumar
  • 659
  • 5
  • 21
2

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()
Vini App
  • 7,339
  • 2
  • 26
  • 43
0

you can use

UIColor(red: CGFloat(255.0), green: CGFloat(255.0), blue: CGFloat(255.0), alpha: CGFloat(255.0))
Hatim
  • 1,516
  • 1
  • 18
  • 30