Created
February 2, 2021 07:20
-
-
Save fhefh2015/4ea84b08b5e4275583c0644e6e4c3722 to your computer and use it in GitHub Desktop.
UIColor(hex: "#f6f6f6")
This file contains hidden or 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 { | |
public convenience init(hex: String) { | |
var r: CGFloat = 0 | |
var g: CGFloat = 0 | |
var b: CGFloat = 0 | |
var a: CGFloat = 1 | |
let hexColor = hex.replacingOccurrences(of: "#", with: "") | |
let scanner = Scanner(string: hexColor) | |
var hexNumber: UInt64 = 0 | |
var valid = false | |
if scanner.scanHexInt64(&hexNumber) { | |
if hexColor.count == 8 { | |
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255 | |
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 | |
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 | |
a = CGFloat(hexNumber & 0x000000ff) / 255 | |
valid = true | |
} | |
else if hexColor.count == 6 { | |
r = CGFloat((hexNumber & 0xff0000) >> 16) / 255 | |
g = CGFloat((hexNumber & 0x00ff00) >> 8) / 255 | |
b = CGFloat(hexNumber & 0x0000ff) / 255 | |
valid = true | |
} | |
} | |
#if DEBUG | |
assert(valid, "UIColor initialized with invalid hex string") | |
#endif | |
self.init(red: r, green: g, blue: b, alpha: a) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment