Skip to content

Instantly share code, notes, and snippets.

@yannickl
Last active September 16, 2023 03:55
Show Gist options
  • Save yannickl/16f0ed38f0698d9a8ae7 to your computer and use it in GitHub Desktop.
Save yannickl/16f0ed38f0698d9a8ae7 to your computer and use it in GitHub Desktop.
Hex string <=> UIColor conversion in Swift
import Foundation
import UIKit
extension UIColor {
convenience init(hexString:String) {
let hexString:NSString = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let scanner = NSScanner(string: hexString)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color:UInt32 = 0
scanner.scanHexInt(&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:1)
}
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 NSString(format:"#%06x", rgb)
}
}
@dzpt
Copy link

dzpt commented Dec 15, 2015

how can i convert NSString from textHexString to UInt?

@jwaldron92
Copy link

Can you give an Example?

@vedadsose
Copy link

Thanks, this is great!

@jwaldron92 You can use it like this: UIColor(hexString: "#363636")

@RajmohanKathiresan
Copy link

@yannickl Awsome !!!

Just in case anyone looking for Swift 3.0 compatibility. Just replace the first two lines with the below mentioned snippet

        let scanner  = Scanner(string: hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))

@eMdOS
Copy link

eMdOS commented Jan 3, 2017

I've been working on these Swift 3 extensions...

... String extension

extension String {
    var hex: Int? {
        return Int(self, radix: 16)
    }
}

... UIColor extension

// MARK: - Hex, Hex + Alpha, RGB, RGB + Alpha

extension UIColor {
    convenience init(hex: Int) {
        self.init(hex: hex, a: 1.0)
    }

    convenience init(hex: Int, a: CGFloat) {
        self.init(r: (hex >> 16) & 0xff, g: (hex >> 8) & 0xff, b: hex & 0xff, a: a)
    }

    convenience init(r: Int, g: Int, b: Int) {
        self.init(r: r, g: g, b: b, a: 1.0)
    }

    convenience init(r: Int, g: Int, b: Int, a: CGFloat) {
        self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: a)
    }

    convenience init?(hexString: String) {
        guard let hex = hexString.hex else {
            return nil
        }
        self.init(hex: hex)
    }
}

... and the result is

let whiteColor: UIColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
let whiteColorFromHex: UIColor = UIColor(hex: 0xffffff)
let whiteColorFromHexString: UIColor? = UIColor(hexString: "ffffff")

whiteColor == whiteColorFromHex // true

whiteColorFromHex == whiteColorFromHexString // true

@jdchdev
Copy link

jdchdev commented Mar 28, 2017

Excelent!!!!! Thnks

@midnightsun052523
Copy link

Great!!!

@midnightsun052523
Copy link

great!!!

@Oyveloper
Copy link

The "let rgb = (int)......" line in the "toHexString()" function gives me an error saying "Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions"

@ismaiI1
Copy link

ismaiI1 commented Jan 5, 2018

is working Swift 4?

@ucotta
Copy link

ucotta commented Mar 14, 2018

A simplified version of eMdOS with Alpha support and optionals. I use it to get the colors from a JSON without worrying if it's defined or not.

extension UIColor {
    convenience init?(hexRGBA: String?) {
        guard let rgba = hexRGBA, let val = Int(rgba.replacingOccurrences(of: "#", with: ""), radix: 16) else {
            return nil
        }
        self.init(red: CGFloat((val >> 24) & 0xff) / 255.0, green: CGFloat((val >> 16) & 0xff) / 255.0, blue: CGFloat((val >> 8) & 0xff) / 255.0, alpha: CGFloat(val & 0xff) / 255.0)
    }
    convenience init?(hexRGB: String?) {
        guard let rgb = hexRGB else {
            return nil
        }
        self.init(hexRGBA: rgb + "ff") // Add alpha = 1.0
    }
}

Usage:

let newColorWithAlpha = UIColor(hexRGBA: "#aabbccdd") ?? UIColor.white
let otherColor = UIColor(hexRGB: "#aabbcc") ?? UIColor.blue

@pvroosendaal
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment