Last active
December 3, 2018 06:16
-
-
Save MrSmart00/2755f9f03fba75548887a68563199a85 to your computer and use it in GitHub Desktop.
UIColor Extension: create with a hex string @Swift4.2
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 { | |
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