-
-
Save ibrennan/c873442f410105de1b57 to your computer and use it in GitHub Desktop.
Handy Swift function for converting a hex value (#FF0000) to Apple UIColor
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 hexStringToUIColor (hex:String) -> UIColor { | |
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString | |
if (cString.hasPrefix("#")) { | |
cString = cString.substringFromIndex(advance(cString.startIndex, 1)) | |
} | |
if (countElements(cString) != 6) { | |
return UIColor.grayColor() | |
} | |
var rgbValue:UInt32 = 0 | |
NSScanner(string: cString).scanHexInt(&rgbValue) | |
return UIColor( | |
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