I put some sample for both conversions, but you can find a lot of code for the transform
To convert from UIColor to a hexadecimal string, you can use the following code:
extension UIColor { var rgbComponents:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { var r:CGFloat = 0 var g:CGFloat = 0 var b:CGFloat = 0 var a:CGFloat = 0 if getRed(&r, green: &g, blue: &b, alpha: &a) { return (r,g,b,a) } return (0,0,0,0) } // hue, saturation, brightness and alpha components from UIColor** var hsbComponents:(hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) { var hue:CGFloat = 0 var saturation:CGFloat = 0 var brightness:CGFloat = 0 var alpha:CGFloat = 0 if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha){ return (hue,saturation,brightness,alpha) } return (0,0,0,0) } var htmlRGBColor:String { return String(format: "#%02x%02x%02x", Int(rgbComponents.red * 255), Int(rgbComponents.green * 255),Int(rgbComponents.blue * 255)) } var htmlRGBaColor:String { return String(format: "#%02x%02x%02x%02x", Int(rgbComponents.red * 255), Int(rgbComponents.green * 255),Int(rgbComponents.blue * 255),Int(rgbComponents.alpha * 255) ) } }
Using an example:
let myColorBlack = UIColor.blackColor().webColor //
For more information you can check: fooobar.com/questions/36961 / ...
https://gist.github.com/yannickl/16f0ed38f0698d9a8ae7
You can save this line inside db and get it when you need it
From HexString to UIColor
extension UIColor { public convenience init?(hexString: String) { let r, g, b, a: CGFloat if hexString.hasPrefix("#") { let start = hexString.startIndex.advancedBy(1) let hexColor = hexString.substringFromIndex(start) if hexColor.characters.count == 8 { let scanner = NSScanner(string: hexColor) var hexNumber: UInt64 = 0 if scanner.scanHexLongLong(&hexNumber) { r = CGFloat((hexNumber & 0xff000000) >> 24) / 255 g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 a = CGFloat(hexNumber & 0x000000ff) / 255 self.init(red: r, green: g, blue: b, alpha: a) return } } } return nil } }
Usage: UIColor (hexString: "# ffe700ff")
Link: https://www.hackingwithswift.com/example-code/uicolor/how-to-convert-a-hex-color-to-a-uicolor
https://github.com/yeahdongcn/UIColor-Hex-Swift
https://gist.github.com/arshad/de147c42d7b3063ef7bc