Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@InsertNetan
Last active December 23, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InsertNetan/4aa7f167704ec168b960 to your computer and use it in GitHub Desktop.
Save InsertNetan/4aa7f167704ec168b960 to your computer and use it in GitHub Desktop.
Swift extension for creating a UIColor from a hex string or number
extension UIColor {
convenience init?(hexString userHexString: String, alpha: CGFloat) {
var hexString:String = userHexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if (hexString.hasPrefix("#")) {
hexString = hexString.substringFromIndex(hexString.startIndex.advancedBy(1))
}
let hexNum = CGFloat(strtoul(hexString, nil, 16))
self.init(hex: hexNum, alpha: alpha)
}
convenience init?(hex: CGFloat, alpha: CGFloat) {
let mask = 0xff
let hex = Int(hex)
let red = CGFloat((hex >> 16) & mask) / 255
let green = CGFloat((hex >> 08) & mask) / 255
let blue = CGFloat((hex >> 00) & mask) / 255
self.init(red: red, green: green , blue: blue, alpha: alpha)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment