Last active
January 20, 2022 11:57
-
-
Save johncodeos/04c345cbde063029ddd3709e74f4f5ff to your computer and use it in GitHub Desktop.
Convert HEX color code to UIColor
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 { | |
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