Skip to content

Instantly share code, notes, and snippets.

@joshuadutton
Last active March 25, 2016 15:42
Show Gist options
  • Save joshuadutton/e8a5fcb9999ff265b636 to your computer and use it in GitHub Desktop.
Save joshuadutton/e8a5fcb9999ff265b636 to your computer and use it in GitHub Desktop.
UIColor Hex Value Extensions
import UIKit
extension UIColor {
static func colorWithHexValue(hexValue: UInt32, alpha: CGFloat) -> UIColor {
let red = CGFloat((hexValue & 0xFF0000) >> 16)
let green = CGFloat((hexValue & 0x00FF00) >> 8)
let blue = CGFloat((hexValue & 0x0000FF))
return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: alpha)
}
static func colorWithHexString(hexString: String, alpha: CGFloat) -> UIColor {
return colorWithHexValue(intFromHexString(hexString), alpha: alpha)
}
static func intFromHexString(hexString: String) -> UInt32 {
var hexInt: UInt32 = 0
let scanner = NSScanner(string: hexString)
scanner.charactersToBeSkipped = NSCharacterSet(charactersInString: "#")
scanner.scanHexInt(&hexInt)
return hexInt
}
}
@joshuadutton
Copy link
Author

Use it like this:

UIColor.colorWithHexValue(0x78B5CA, alpha: 1.0)

UIColor.colorWithHexString("#78B5CA", alpha: 1.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment