Skip to content

Instantly share code, notes, and snippets.

@bduyng
Last active March 16, 2016 09:54
Show Gist options
  • Select an option

  • Save bduyng/8b1dd3f8dac66035fa21 to your computer and use it in GitHub Desktop.

Select an option

Save bduyng/8b1dd3f8dac66035fa21 to your computer and use it in GitHub Desktop.
Extension of UIColor that support HEX color which also included alpha value
extension UIColor {
class func hex(string: String) -> UIColor {
var hex = string.hasPrefix("#")
? String(string.characters.dropFirst())
: string
guard hex.characters.count == 3 || hex.characters.count == 6 || hex.characters.count == 8
else { return UIColor.whiteColor().colorWithAlphaComponent(0.0) }
if hex.characters.count == 3 {
for (index, char) in hex.characters.enumerate() {
hex.insert(char, atIndex: hex.startIndex.advancedBy(index * 2))
}
}
if hex.characters.count == 6 {
hex = "FF" + hex
}
return UIColor(
red: CGFloat((Int(hex, radix: 16)! >> 16) & 0xFF) / 255.0,
green: CGFloat((Int(hex, radix: 16)! >> 8) & 0xFF) / 255.0,
blue: CGFloat((Int(hex, radix: 16)! >> 0) & 0xFF) / 255.0,
alpha: CGFloat((Int(hex, radix: 16)! >> 24) & 0xFF) / 255.0)
}
}
// Example
UIColor.hex("#80000000") // 0x80 is alpha value(about 50%)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment