Last active
November 24, 2015 11:08
-
-
Save pablogm/206fe8e4ae04b8fdb062 to your computer and use it in GitHub Desktop.
Swift extension to get UIColor from it hex representation
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
// | |
// 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