Skip to content

Instantly share code, notes, and snippets.

@perlguy99
Created January 8, 2019 16:44
Show Gist options
  • Save perlguy99/1f83a93b223c6b333794f267670c9143 to your computer and use it in GitHub Desktop.
Save perlguy99/1f83a93b223c6b333794f267670c9143 to your computer and use it in GitHub Desktop.
UIColor extension for HEX values
extension UIColor {
convenience init?(hexString: String) {
var chars = Array(hexString.hasPrefix("#") ? hexString.dropFirst() : hexString[...])
let red, green, blue, alpha: CGFloat
switch chars.count {
case 3:
chars = chars.flatMap { [$0, $0] }
fallthrough
case 6:
chars = ["F","F"] + chars
fallthrough
case 8:
alpha = CGFloat(strtoul(String(chars[0...1]), nil, 16)) / 255
red = CGFloat(strtoul(String(chars[2...3]), nil, 16)) / 255
green = CGFloat(strtoul(String(chars[4...5]), nil, 16)) / 255
blue = CGFloat(strtoul(String(chars[6...7]), nil, 16)) / 255
default:
return nil
}
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment