Skip to content

Instantly share code, notes, and snippets.

@migueltg
Last active April 13, 2020 12:29
Show Gist options
  • Save migueltg/a6ab2b5909fb34b4aad22897bfc76f97 to your computer and use it in GitHub Desktop.
Save migueltg/a6ab2b5909fb34b4aad22897bfc76f97 to your computer and use it in GitHub Desktop.
Swift function that returns a UIColor from a color in hexadecimal
func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
let index = cString.index(cString.startIndex, offsetBy: 1)
cString = cString.substring(from: index)
}
if (cString.characters.count != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
@JonathandelaSen
Copy link

Bravo!

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