How to convert HEX colors to UIColor in Swift 4?

There are many situations when you want to create an UIColor object from a hex color string. In this post, we provide a code sample that will help you convert hex colors to UIColor objects. While generally, you can get away with this by manually converting the hex code to RGB (using an online converter, for example), there are scenarios where your colors are dynamic, so you’ll need a utility method that converts the hex code to an RGB color in Swift 4.

We encountered this problem when we wanted to fetch the colors for some of our iOS native views, dynamically, from a remote database (Firebase, in our case). While you could pass the RGB values as well, it’s much more annoying to parse 3 server fields (RGB), rather than just one (hex). So we came up with this short UIColor extension, that compiles in Swift 4:

import Foundation
import UIKit

extension UIColor {
    convenience init(hexString: String, alpha: CGFloat = 1.0) {
        let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        let scanner = Scanner(string: hexString)

        if (hexString.hasPrefix("#")) {
            scanner.scanLocation = 1
        }

        var color: UInt32 = 0
        scanner.scanHexInt32(&color)

        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask

        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0

        self.init(red:red, green:green, blue:blue, alpha:alpha)
    }

    func toHexString() -> String {
        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0

        getRed(&r, green: &g, blue: &b, alpha: &a)

        let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0

        return String(format:"#%06x", rgb)
    }
}

To use it, simply create your RGB colors like this

let color = UIColor(hexString: "#3f3f3f")

You can download the Swift 4 source code from Github as well. Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *