Created
February 5, 2016 17:18
-
-
Save UjwalManjunath/4969c15b130334df320d to your computer and use it in GitHub Desktop.
creates a UIColor from a hex string
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 { | |
class func HTSDColorWithHexString (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