Skip to content

Instantly share code, notes, and snippets.

@vialyx
Created February 21, 2018 10:20
Show Gist options
  • Save vialyx/3dc1c1bebac4f690a69173280bc4e0f5 to your computer and use it in GitHub Desktop.
Save vialyx/3dc1c1bebac4f690a69173280bc4e0f5 to your computer and use it in GitHub Desktop.
import UIKit
extension UIColor {
convenience init(hex: String) {
var cString: String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if cString.hasPrefix("#") {
cString.remove(at: cString.startIndex)
}
if cString.count != 6 {
self.init(white: 1.0, alpha: 1.0)
} else {
var rgbValue: UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
self.init(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment