Skip to content

Instantly share code, notes, and snippets.

@geosava
Forked from shadcn/gist:de147c42d7b3063ef7bc
Last active August 29, 2015 14:22
Show Gist options
  • Save geosava/674233bcb1f100418ce9 to your computer and use it in GitHub Desktop.
Save geosava/674233bcb1f100418ce9 to your computer and use it in GitHub Desktop.
// Creates a UIColor from a Hex string.
func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = cString.substringFromIndex(1)
}
if (countElements(cString) != 6) {
return UIColor.grayColor()
}
var rString = cString.substringToIndex(2)
var gString = cString.substringFromIndex(2).substringToIndex(2)
var bString = cString.substringFromIndex(4).substringToIndex(2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner.scannerWithString(rString).scanHexInt(&r)
NSScanner.scannerWithString(gString).scanHexInt(&g)
NSScanner.scannerWithString(bString).scanHexInt(&b)
return UIColor(red: Float(r) / 255.0, green: Float(g) / 255.0, blue: Float(b) / 255.0, alpha: Float(1))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment