Last Updated: February 25, 2016
· isuruj

UIColor With Hex Values

There is no built-in method to get UIColor given a hex value. I came across my friend @itseranga's Coderwall tip on how to do just that. He uses a simple function to do this.

Since Swift supports extensions, we can have this same function in a more elegant way.

I simply created an extension of UIColor and added a convenience init.

import Foundation
import UIKit

extension UIColor {

    convenience init(hex: UInt32, alpha: CGFloat) {
        let red = CGFloat((hex & 0xFF0000) >> 16)/256.0
        let green = CGFloat((hex & 0xFF00) >> 8)/256.0
        let blue = CGFloat(hex & 0xFF)/256.0

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

Now we can use this like you'd normally use the UIColor class.

view.backgroundColor = UIColor(hex: 0x444444, alpha: 0.7)


Say Thanks