Last active
August 29, 2015 14:24
-
-
Save rafaelcpalmeida/6a4e60cba900db0f5a46 to your computer and use it in GitHub Desktop.
Convert a Hex string to UIColor in Swift 1.2
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: NSString) -> UIColor | |
{ | |
var cString: NSString = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString | |
if(count(cString as String) < 6) | |
{ | |
return UIColor.grayColor() | |
} | |
if(cString.hasPrefix("0X")) | |
{ | |
cString = cString.substringFromIndex(advance(0, 2)) | |
} | |
if(count(cString as String) != 6) | |
{ | |
return UIColor.grayColor() | |
} | |
var rString = cString.substringWithRange(NSRange(location: 0, length: 2)) | |
var gString = cString.substringWithRange(NSRange(location: 2, length: 2)) | |
var bString = cString.substringWithRange(NSRange(location: 4, length: 2)) | |
var r,g,b: CUnsignedInt | |
NSScanner(string: rString).scanHexInt(&r) | |
NSScanner(string: gString).scanHexInt(&g) | |
NSScanner(string: bString).scanHexInt(&b) | |
return UIColor(red: CGFloat(Float(r) / 255.0), green: CGFloat(Float(g) / 255.0), blue: CGFloat(Float(b) / 255.0), alpha: CGFloat(Float(1))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment