Skip to content

Instantly share code, notes, and snippets.

@johncodeos
Last active January 20, 2022 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johncodeos/04c345cbde063029ddd3709e74f4f5ff to your computer and use it in GitHub Desktop.
Save johncodeos/04c345cbde063029ddd3709e74f4f5ff to your computer and use it in GitHub Desktop.
Convert HEX color code to UIColor
extension UIColor {
static func colorFromHex(_ hex: String) -> UIColor {
var hexString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if hexString.hasPrefix("#") {
hexString.remove(at: hexString.startIndex)
}
if hexString.count != 6 {
return UIColor.magenta
}
var rgb: UInt32 = 0
Scanner(string: hexString).scanHexInt32(&rgb)
return UIColor(red: CGFloat((rgb & 0xFF0000) >> 16)/255,
green: CGFloat((rgb & 0x00FF00) >> 8)/255,
blue: CGFloat(rgb & 0x0000FF)/255,
alpha: 1.0)
}
}
// How to use it:
myView.backgroundColor = UIColor.colorFromHex("#BC214B")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment