Using HEX Color Values in SwiftUI

Most often, when working on implementing a design in SwiftUI, you'll be faced with the challenge of somehow converting a HEX color value to something that is usable in SwiftUI.

This seemingly simple task is surprisingly hard to achieve. Much harder than it probably should be because, for some reason, Apple one day decided to completely ignore the fact that HEX colors exist, even though it's probably the easiest and most straightforward way to communicate a color value.

No need to bury your head in the sand, though. If Tim Apple ain't gonna do it, we're gonna do it ourselves.

All we have to do is create an extension for Color, extract the RGB values from the HEX code, and use those to call the appropriate initializer.

import SwiftUI

extension Color {
    init(hex: String) {
        let hex = hex.trimmingCharacters(in: CharacterSet(charactersIn: "#"))
        let rgbValue = UInt32(hex, radix: 16)
        let r = Double((rgbValue! & 0xFF0000) >> 16) / 255
        let g = Double((rgbValue! & 0x00FF00) >> 8) / 255
        let b = Double(rgbValue! & 0x0000FF) / 255
        self.init(red: r, green: g, blue: b)
    }
}

Voilà! Now you can use the newly created initializer like so.

Text("Hello, SwiftUI!")
	.font(.largeTitle)
	.padding()
	.background(Color(hex: "#3E3AFF"))

Hope that helps. It does help me.

XOXO, Christian 👨🏻‍💻