Created
January 12, 2018 20:24
-
-
Save karstengresch/2a81245a5caeb6b963d035a9ae452c16 to your computer and use it in GitHub Desktop.
Swift 4: UIColor(hex: String) extension
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
// Inspired by https://stackoverflow.com/questions/24263007/how-to-use-hex-colour-values, merging Swift 4 + extension examples | |
extension UIColor { | |
convenience init (hex:String) { | |
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() | |
if (cString.hasPrefix("#")) { | |
cString.remove(at: cString.startIndex) | |
} | |
if ((cString.count) != 6) { | |
self.init(cgColor: UIColor.gray.cgColor) | |
} else { | |
var rgbValue:UInt32 = 0 | |
Scanner(string: cString).scanHexInt32(&rgbValue) | |
self.init( | |
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, | |
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, | |
blue: CGFloat(rgbValue & 0x0000FF) / 255.0, | |
alpha: CGFloat(1.0) | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment