Skip to content

Instantly share code, notes, and snippets.

@MrSmart00
Last active December 3, 2018 06:16
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 MrSmart00/2755f9f03fba75548887a68563199a85 to your computer and use it in GitHub Desktop.
Save MrSmart00/2755f9f03fba75548887a68563199a85 to your computer and use it in GitHub Desktop.
UIColor Extension: create with a hex string @Swift4.2
extension UIColor {
convenience init(hex: String) {
let hexStr = hex.lowercased().replacingOccurrences(of: "0x", with: "")
let hexmap = hexStr.map { String($0) }
+ Array(repeating: "0", count: max(6 - hexStr.count, 0))
+ Array(repeating: "f", count: max(8 - max(6, hexStr.count), 0))
let split = stride(from: 0, to: hexmap.count, by: 2)
.map { hexmap[$0..<$0+2]
.reduce(into: String()) { $0 += $1 } }
let hexRGB = split.map { CGFloat(Int($0, radix: 16) ?? 0) / 255.0 }
self.init(red: hexRGB[0],
green: hexRGB[1],
blue: hexRGB[2],
alpha: hexRGB[3])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment