As a web developer by day, my world revolves around the 6 character hexadecimal color codes that we use on web pages. For example, #FF0000 is the reddest of the reds.
Unfortunately, UIColor doesn't support a hexadecimal constructor, only CGFloat red/green/blue values. So extensions to the rescue!
Below you can find an extension to UIColor that takes a hexadecimal value as its color and creates an appropriate UIColor object: let color = UIColor(hex: "1289AB")
Note that it requires the Swift extension from my previous article about Swift substrings.
//
// UIColor+CKHexColors.swift
//
import Foundation
import UIKit
extension UIColor {
// constructor takes a hex color as a string in the format: "1289AB"
convenience init(hexColor: String) {
let redColor = UIColor.hexColorToFloat(hexColor[0...1])
let greenColor = UIColor.hexColorToFloat(hexColor[2...3])
let blueColor = UIColor.hexColorToFloat(hexColor[4...5])
self.init(red: redColor, green: greenColor, blue: blueColor, alpha: 1.0)
}
// converts a hex color string to a float number
private class func hexColorToFloat(hexColor: String) -> CGFloat {
let char0 = hexColor[0...0].uppercaseString
let char1 = hexColor[1...1].uppercaseString
let value0 = UIColor.hexToInt(char0)
let value1 = UIColor.hexToInt(char1)
let colorValue = (value0 * 16) + value1
let floatValue: CGFloat = CGFloat(colorValue) / 255.0
return floatValue
}
// converts a hex character to an integer
private class func hexToInt(hex: String) -> Int {
var intValue = 0
switch hex {
case "A":
intValue = 10
case "B":
intValue = 11
case "C":
intValue = 12
case "D":
intValue = 13
case "E":
intValue = 14
case "F":
intValue = 15
default:
intValue = Int(hex) ?? 0
}
return intValue
}
}