diff --git a/ACKategories-iOS/UIColorExtensions.swift b/ACKategories-iOS/UIColorExtensions.swift index 376da899..b5962b96 100644 --- a/ACKategories-iOS/UIColorExtensions.swift +++ b/ACKategories-iOS/UIColorExtensions.swift @@ -16,17 +16,38 @@ public extension UIColor { } /** - Initialize color from hex string (eg. "#ff00ff"). Leading '#' is mandatory. + Initialize color from hex string (eg. "#ff00ff"). Leading '#' is not mandatory. - parameter hexString: Hex string to create color from */ - convenience init(hexString: String) { - var rgbValue: UInt32 = 0 - let scanner = Scanner(string: hexString) - scanner.scanLocation = 1 // bypass '#' character - scanner.scanHexInt32(&rgbValue) - self.init(hex: rgbValue) - } + convenience init(hexString: String) { + var hexSanitized = hexString.trimmingCharacters(in: .whitespacesAndNewlines) + hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "") + + var rgb: UInt64 = 0 + + var r: CGFloat = 0.0 + var g: CGFloat = 0.0 + var b: CGFloat = 0.0 + let a: CGFloat = 1.0 + + let length = hexSanitized.count + + guard Scanner(string: hexSanitized).scanHexInt64(&rgb) else { + self.init() + return + } + + if length == 6 { + r = CGFloat((rgb & 0xFF0000) >> 16) / 255.0 + g = CGFloat((rgb & 0x00FF00) >> 8) / 255.0 + b = CGFloat(rgb & 0x0000FF) / 255.0 + } else { + self.init() + } + + self.init(red: r, green: g, blue: b, alpha: a) + } /** Returns color as hex string (eg. '#ff00ff') or nil if RGBA components couldn't be loaded.