Created
February 11, 2021 11:56
-
-
Save budidino/431f966f6c22a4f7ad06dcf8619bfd08 to your computer and use it in GitHub Desktop.
init UIColor using hex string
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
/* | |
// convenience method for initializing UIColor with HEX value | |
UIColor("#ff0000") // with # | |
UIColor("ff0000") // without # | |
UIColor("ff0000", alpha: 0.5) // using optional alpha value | |
*/ | |
extension UIColor { | |
convenience init(_ hex: String, alpha: CGFloat = 1.0) { | |
var cString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() | |
if cString.hasPrefix("#") { cString.removeFirst() } | |
if cString.count != 6 { | |
self.init("ff0000") // return red color for wrong hex input | |
return | |
} | |
var rgbValue: UInt64 = 0 | |
Scanner(string: cString).scanHexInt64(&rgbValue) | |
self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, | |
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, | |
blue: CGFloat(rgbValue & 0x0000FF) / 255.0, | |
alpha: alpha) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment