-
-
Save resand/eb394e7e564a14a64812b605de08a477 to your computer and use it in GitHub Desktop.
Convert a Hex string to UIColor in Swift
This file contains hidden or 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
| // 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