Created
January 8, 2019 16:44
-
-
Save perlguy99/1f83a93b223c6b333794f267670c9143 to your computer and use it in GitHub Desktop.
UIColor extension for HEX values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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