make a uicolor from hex in swift

You can easily create a UIColor from a hex color string in Swift using an extension on UIColor. Here's the code for the extension:

main.swift
extension UIColor {
    convenience init?(hexString: String) {
        let r, g, b, a: CGFloat

        if hexString.hasPrefix("#") {
            let start = hexString.index(hexString.startIndex, offsetBy: 1)
            let hexColor = String(hexString[start...])

            if hexColor.count == 8 {
                let scanner = Scanner(string: hexColor)
                var hexNumber: UInt64 = 0

                if scanner.scanHexInt64(&hexNumber) {
                    r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                    g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                    b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
                    a = CGFloat(hexNumber & 0x000000ff) / 255

                    self.init(red: r, green: g, blue: b, alpha: a)
                    return
                }
            }
        }

        return nil
    }
}
891 chars
28 lines

To use this extension, simply create a new UIColor instance using the hexString parameter:

main.swift
let myColor = UIColor(hexString: "#ff0000")
44 chars
2 lines

This will create a new UIColor instance with the red color #FF0000 (equivalent to UIColor.red).

related categories

gistlibby LogSnag