Member-only story

Creating a UIColor from hexadecimal number or string

Mr.Javed Multani
1 min readOct 5, 2020

--

You can create a UIColor from a hexadecimal number or string, e.g. 0xff00cc, “#FFFFFF”

Swift

Int Value

extension UIColor {
convenience init(hex: Int, alpha: CGFloat = 1.0) {
let r = CGFloat((hex >> 16) & 0xff) / 255
let g = CGFloat((hex >> 08) & 0xff) / 255
let b = CGFloat((hex >> 00) & 0xff) / 255
self.init(red: r, green: g, blue: b, alpha: alpha)} }

Example:

let color = UIColor(hex: 0xff00cc, alpha: 1.0)

Note that for alpha the default value of 1.0 is provided, so it can be used as follows:

let color = UIColor(hex: 0xff00cc)

--

--

Mr.Javed Multani
Mr.Javed Multani

Written by Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer

No responses yet