Skip to content

Instantly share code, notes, and snippets.

@blixt
Last active July 28, 2021 05:19
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save blixt/821a0748257dc8d3581f to your computer and use it in GitHub Desktop.
Save blixt/821a0748257dc8d3581f to your computer and use it in GitHub Desktop.
A Swift String extension that converts a hexadecimal color to a UIColor.
import UIKit
extension String {
var hexColor: UIColor? {
let hex = self.stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet)
var int = UInt32()
guard NSScanner(string: hex).scanHexInt(&int) else {
return nil
}
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
return nil
}
return UIColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
"#f00".hexColor // r 1.0 g 0.0 b 0.0 a 1.0
"#be1337".hexColor // r 0.745 g 0.075 b 0.216 a 1.0
"#12345678".hexColor // r 0.204 g 0.337 b 0.471 a 0.071
"#hihihi".hexColor // nil
@DeFrenZ
Copy link

DeFrenZ commented Oct 6, 2015

I would rather make first an UIColor throwable init (so that you can specify what went wrong in the parsing) and then use that (with try?) for the String var

@ohcrider
Copy link

nice

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