Skip to content

Instantly share code, notes, and snippets.

@DanielCardonaRojas
Created July 14, 2020 20:11
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 DanielCardonaRojas/c7605d8673ec1e5b67f2daae3ac40ccc to your computer and use it in GitHub Desktop.
Save DanielCardonaRojas/c7605d8673ec1e5b67f2daae3ac40ccc to your computer and use it in GitHub Desktop.
UIColor+Extensions #ios #swift #UIColor
extension UIColor {
public convenience init?(hex: String) {
let r: CGFloat
let g: CGFloat
let b: CGFloat
let a: CGFloat
let start = hex.index(hex.startIndex, offsetBy: hex.hasPrefix("#") ? 1 : 0)
var hexColor = String(hex[start...])
if hexColor.count == 6 { hexColor += "FF" }
if hexColor.count == 8 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff00_0000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff_0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000_ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x0000_00ff) / 255
self.init(red: r, green: g, blue: b, alpha: a)
return
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment