How to convert a hex color to a UIColor

This snippet of code takes a hex color string as input and creates a UIColor object as a result. It expects the hex color string format of #RRGGBB.

extension UIColor {
    
    public convenience init(hex: String, alpha: CGFloat = 1) {
        assert(hex.hasPrefix("#"),  "Expected hex string of format #RRGGBB")
        
        let start = hex.index(hex.startIndex, offsetBy: 1)
        let hexColor = String(hex[start...])
        
        let scanner = Scanner(string: hexColor)
        var hexNumber: UInt64 = 0
        
        scanner.scanHexInt64(&hexNumber)
        
        self.init(red:   CGFloat((hexNumber & 0xFF0000) >> 16) / 255.0,
                  green: CGFloat((hexNumber & 0x00FF00) >>  8) / 255.0,
                  blue:  CGFloat((hexNumber & 0x0000FF)      ) / 255.0,
                  alpha: alpha)
    }
}

To use the above extension code

UIColor(hex: "#ABABAB")
// or
UIColor(hex: "#ABABAB", alpha: 0.5)

Posted

in

by

Tags:

Comments

Leave a comment