Skip to content

Instantly share code, notes, and snippets.

@pablogm
Last active November 24, 2015 11:08
Show Gist options
  • Save pablogm/206fe8e4ae04b8fdb062 to your computer and use it in GitHub Desktop.
Save pablogm/206fe8e4ae04b8fdb062 to your computer and use it in GitHub Desktop.
Swift extension to get UIColor from it hex representation
//
// UIColor+Hex.swift
// Swift extensions
//
import Foundation
import UIKit
enum ColorComponentError: ErrorType {
case InvalidRedComponent
case InvalidGreenComponent
case InvalidBlueComponent
}
extension UIColor {
convenience init(red: UInt8, green: UInt8, blue: UInt8) throws {
if red < 0 || red > 255 {
throw ColorComponentError.InvalidRedComponent
}
if green < 0 || green > 255 {
throw ColorComponentError.InvalidGreenComponent
}
if blue < 0 || blue > 255 {
throw ColorComponentError.InvalidBlueComponent
}
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(hex:Int) {
self.init(hex: hex, alpha:1.0)
}
convenience init(hex:Int, alpha: Double) {
self.init(
red: CGFloat((hex >> 16) & 0xff) / 255.0,
green: CGFloat((hex >> 8) & 0xff) / 255.0,
blue: CGFloat(hex & 0xff) / 255.0,
alpha: CGFloat(alpha))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment