From f230291e4787eb583f1fa5e8a0435e2b71943690 Mon Sep 17 00:00:00 2001 From: "Pfeil, Scott Robert" Date: Fri, 28 Feb 2020 11:36:14 -0500 Subject: [PATCH] color --- MVMCoreUI/CustomPrimitives/Color.swift | 46 +++++++++++++++++--------- 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/MVMCoreUI/CustomPrimitives/Color.swift b/MVMCoreUI/CustomPrimitives/Color.swift index 165fa8ad..f06b337c 100644 --- a/MVMCoreUI/CustomPrimitives/Color.swift +++ b/MVMCoreUI/CustomPrimitives/Color.swift @@ -62,6 +62,14 @@ public final class Color: Codable { determineRGBA() } + public init?(colorString: String) throws { + let components = try Color.getColorComponents(for: colorString) + self.uiColor = components.color + hex = components.hex + name = components.name ?? "" + determineRGBA() + } + //-------------------------------------------------- // MARK: - Codable Initializers //-------------------------------------------------- @@ -69,21 +77,10 @@ public final class Color: Codable { required public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let colorString = try container.decode(String.self) - - if colorString.hasPrefix("#") { - hex = colorString.replacingOccurrences(of: "#", with: "") - } else { - guard let hex = UIColor.names[colorString]?.hex else { throw ColorError.badName(reason: "Check the spelling of your color.") } - self.hex = hex.replacingOccurrences(of: "#", with: "") - name = colorString - } - - if hex.count == 8 { - uiColor = UIColor.getColorWithTransparencyBy(hex: hex) - } else { - uiColor = UIColor.getColorBy(hex: hex) - } - + let components = try Color.getColorComponents(for: colorString) + self.uiColor = components.color + hex = components.hex + name = components.name ?? "" determineRGBA() } @@ -95,6 +92,25 @@ public final class Color: Codable { //-------------------------------------------------- // MARK: - Methods //-------------------------------------------------- + private static func getColorComponents(for colorString: String) throws -> (color: UIColor, hex: String, name: String?) { + var color: UIColor + var hex: String + var name: String? + if colorString.hasPrefix("#") { + hex = colorString.replacingOccurrences(of: "#", with: "") + } else { + guard let hexString = UIColor.names[colorString]?.hex else { throw ColorError.badName(reason: "Check the spelling of your color.") } + hex = hexString.replacingOccurrences(of: "#", with: "") + name = colorString + } + + if hex.count == 8 { + color = UIColor.getColorWithTransparencyBy(hex: hex) + } else { + color = UIColor.getColorBy(hex: hex) + } + return (color, hex, name) + } public func convertHexToFloat(start: String.Index, end: String.Index) -> CGFloat {