How To Set Custom Colors In Swift Programmatically

By Eddy Chung

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, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts