Initialize UIColor from RGB hex in Swift

Want to initialize a UIColor object from a hex code?

Create a new Swift class named “UIColor+FromRGB.swift” with the following content:

import UIKit

extension UIColor {

    static func fromRGB(colorCode: String, alpha: Float = 1.0) -> UIColor {
        let scanner = NSScanner(string:colorCode)
        var color:UInt32 = 0;
        scanner.scanHexInt(&color)
        
        let mask = 0x000000FF
        let r = CGFloat(Float(Int(color >> 16) & mask)/255.0)
        let g = CGFloat(Float(Int(color >> 8) & mask)/255.0)
        let b = CGFloat(Float(Int(color) & mask)/255.0)
        
        return UIColor(red: r, green: g, blue: b, alpha: CGFloat(alpha))
    }
    
    static func fromRGB(colorCode: UInt) -> UIColor {
        
        let mask = 0x000000FF
        let r = CGFloat(Float(Int(colorCode >> 16) & mask)/255.0)
        let g = CGFloat(Float(Int(colorCode >> 8) & mask)/255.0)
        let b = CGFloat(Float(Int(colorCode) & mask)/255.0)
        
        return UIColor(red: r, green: g, blue: b, alpha: CGFloat(1.0))
    }
}

Initializing a UIColor object then is now a matter of a one-liner, e.g.:

 filter.backgroundColor = UIColor.fromRGB("00B997");

 

Leave a comment

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.