UInt
has a convenience initializer to convert a hex string to its hex value
func color(from hexString : String) -> CGColor
{
if let rgbValue = UInt(hexString, radix: 16) {
let red = CGFloat((rgbValue >> 16) & 0xff) / 255
let green = CGFloat((rgbValue >> 8) & 0xff) / 255
let blue = CGFloat((rgbValue ) & 0xff) / 255
return UIColor(red: red, green: green, blue: blue, alpha: 1.0).cgColor
} else {
return UIColor.black.cgColor
}
}
Now map the string array to the color array
let hexColors = ["6909A1", "7552D1", "59B0DC", "62E3CC"]
let gradientColors = hexColors.map { color(from:$0) }
or alternatively in an UIColor
extension
extension UIColor {
convenience init(hexString : String)
{
if let rgbValue = UInt(hexString, radix: 16) {
let red = CGFloat((rgbValue >> 16) & 0xff) / 255
let green = CGFloat((rgbValue >> 8) & 0xff) / 255
let blue = CGFloat((rgbValue ) & 0xff) / 255
self.init(red: red, green: green, blue: blue, alpha: 1.0)
} else {
self.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
}
}
}
let hexColors = ["6909A1", "7552D1", "59B0DC", "62E3CC"]
let gradientColors = hexColors.map { UIColor(hexString:$0).cgColor }