From 8ed1876c7e5a280236b3da0b02158352de1d357a Mon Sep 17 00:00:00 2001 From: Ivan Smolin Date: Fri, 9 Sep 2016 12:28:05 +0300 Subject: [PATCH] UIColor+Hex from string fix --- .../Extensions/UIColor/UIColor+Hex.swift | 34 +++++++++++-------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/LeadKit/LeadKit/Extensions/UIColor/UIColor+Hex.swift b/LeadKit/LeadKit/Extensions/UIColor/UIColor+Hex.swift index 9d31250d..b8ab108f 100644 --- a/LeadKit/LeadKit/Extensions/UIColor/UIColor+Hex.swift +++ b/LeadKit/LeadKit/Extensions/UIColor/UIColor+Hex.swift @@ -87,28 +87,32 @@ public extension UIColor { public convenience init?(hexString: String, alpha: CGFloat = 1) { let hexStr = hexString.hasPrefix("#") ? hexString.substringFromIndex(hexString.startIndex.advancedBy(1)) : hexString - switch hexStr.characters.count { - case 3: + let charactersCount = hexStr.characters.count + + switch charactersCount { + case 3, 4: if let hex = UInt16(hexStr, radix: 16) { - self.init(hex3: hex, alpha: alpha) + if charactersCount == 3 { + self.init(hex3: hex, alpha: alpha) + } else { + self.init(hex4: hex) + } + } else { + return nil } - case 4: - if let hex = UInt16(hexStr, radix: 16) { - self.init(hex4: hex) - } - case 6: + case 6, 8: if let hex = UInt32(hexStr, radix: 16) { - self.init(hex6: hex, alpha: alpha) - } - case 8: - if let hex = UInt32(hexStr, radix: 16) { - self.init(hex8: hex) + if charactersCount == 6 { + self.init(hex6: hex, alpha: alpha) + } else { + self.init(hex8: hex) + } + } else { + return nil } default: return nil } - - return nil } }