Skip to content

Instantly share code, notes, and snippets.

@ollieatkinson
Created August 18, 2015 10:51
Show Gist options
  • Save ollieatkinson/d1c76c6c7617583c3000 to your computer and use it in GitHub Desktop.
Save ollieatkinson/d1c76c6c7617583c3000 to your computer and use it in GitHub Desktop.
UIColor+Hex
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