How To Set Custom Colors In Swift Programmatically

Your designer gives your a color and you need to set it in code. Here’s how to do it.

How To Set Custom RGB Colors In Swift Programmatically

If you know your RGB values you can simply set the background color by doing:

view.backgroundColor = UIColor(red: 1.00, green: 1.00, blue: 1.00, alpha: 1.00)

Or text color by doing:

view.textColor = UIColor(red: 1.00, green: 1.00, blue: 1.00, alpha: 1.00)

You can also convert a HEX color to UIColor by using these tools:

How To Set Custom HEX Colors In Swift Programmatically

You can use this function to covert a HEX color to a RGB:

func getUIColor(hex: String, alpha: Double = 1.0) -> UIColor? {
    var cleanString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cleanString.hasPrefix("#")) {
        cleanString.remove(at: cleanString.startIndex)
    }

    if ((cleanString.count) != 6) {
        return nil
    }

    var rgbValue: UInt32 = 0
    Scanner(string: cleanString).scanHexInt32(&rgbValue)

    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}

Then you can call it like so:

var color = getUIColor("#c1c1c1")
If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts