Skip to content

Instantly share code, notes, and snippets.

@joeltrew
Created May 4, 2020 20:03
Show Gist options
  • Save joeltrew/a42ce717f9eb9bacdcd7c4600a8deee8 to your computer and use it in GitHub Desktop.
Save joeltrew/a42ce717f9eb9bacdcd7c4600a8deee8 to your computer and use it in GitHub Desktop.
Hex String to UIColor, both static and dynamic string support
extension UIColor {
convenience init(hex: StaticString) {
let hex = String(hex.description)
guard let rgb = UIColor.rgbValue(from: hex) else {
preconditionFailure("Invalid hex color string provided")
}
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
convenience init?(hex: String) {
let hex = String(hex.description)
guard let rgb = UIColor.rgbValue(from: hex) else {
return nil
}
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
private static func rgbValue(from hex: String) -> UInt64? {
var cString: String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return nil
}
var rgbValue: UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
return rgbValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment