UIColor extension for RGB Hex in Swift

Written on:July 22, 2014
Comments
Add One

We had a great boot camp this weekend at the Dallas iOS Swift Boot Camp! One question was how to make a UIColor from a hex value. I personally think hex colors are so much easier to deal with.

Here is the little gem for you in swift:

import UIKit

extension UIColor {
    class func colorWithRGBHex(hex: Int, alpha: Float = 1.0) -> UIColor {
        let r = Float((hex >> 16) & 0xFF)
        let g = Float((hex >> 8) & 0xFF)
        let b = Float((hex) & 0xFF)

        return UIColor(red: CGFloat(r / 255.0), green: CGFloat(g / 255.0), blue:CGFloat(b / 255.0), alpha: CGFloat(alpha))
    }
}

Call it like this:

var whiteColor = UIColor.colorWithRGBHex(0xffffff)

Here is the source: UIColor+RGBHex.swift.zip

Leave a Comment