Created
August 18, 2015 10:51
-
-
Save ollieatkinson/d1c76c6c7617583c3000 to your computer and use it in GitHub Desktop.
UIColor+Hex
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
import UIKit | |
extension UIColor { | |
static func colorWithHex(hex RGBAHex: String) -> UIColor? { | |
if !RGBAHex.hasPrefix("#") { | |
return nil | |
} | |
let index = advance(RGBAHex.startIndex, 1) | |
let hex = RGBAHex.substringFromIndex(index) | |
let scanner = NSScanner(string: hex) | |
var hexValue: CUnsignedLongLong = 0 | |
if scanner.scanHexLongLong(&hexValue) { | |
let r = CGFloat((hexValue >> 24) & 0xFF) / 255 | |
let g = CGFloat((hexValue >> 16) & 0xFF) / 255 | |
let b = CGFloat((hexValue >> 8) & 0xFF) / 255 | |
let a = CGFloat((hexValue >> 0) & 0xFF) / 255 | |
return UIColor(red: r, green: g, blue: b, alpha: a) | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment