Skip to content

Instantly share code, notes, and snippets.

@budidino
Created February 11, 2021 11:56
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 budidino/431f966f6c22a4f7ad06dcf8619bfd08 to your computer and use it in GitHub Desktop.
Save budidino/431f966f6c22a4f7ad06dcf8619bfd08 to your computer and use it in GitHub Desktop.
init UIColor using hex string
/*
// convenience method for initializing UIColor with HEX value
UIColor("#ff0000") // with #
UIColor("ff0000") // without #
UIColor("ff0000", alpha: 0.5) // using optional alpha value
*/
extension UIColor {
convenience init(_ hex: String, alpha: CGFloat = 1.0) {
var cString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if cString.hasPrefix("#") { cString.removeFirst() }
if cString.count != 6 {
self.init("ff0000") // return red color for wrong hex input
return
}
var rgbValue: UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: alpha)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment