Created
October 14, 2016 13:33
-
-
Save gregszero/a2e2adb86473c086d786d0b98b5a961b to your computer and use it in GitHub Desktop.
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
func colorWithHexString (hex:String) -> UIColor { | |
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString | |
if (cString.hasPrefix("#")) { | |
cString = (cString as NSString).substringFromIndex(1) | |
} | |
if (cString.characters.count != 6) { | |
return UIColor.grayColor() | |
} | |
let rString = (cString as NSString).substringToIndex(2) | |
let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2) | |
let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2) | |
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; | |
NSScanner(string: rString).scanHexInt(&r) | |
NSScanner(string: gString).scanHexInt(&g) | |
NSScanner(string: bString).scanHexInt(&b) | |
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment