Search code examples
iosswiftcolorsswiftuibackground-color

How to use Color with RGB or hex value in SwiftUI using Swift 5?


I am currently trying to change the background color of a Label in SwiftUI. As far as I know, SwiftUI takes a View as the parameter for the background Modifier.

However, I encountered a problem I am not able to fix:

I would like to change the background color of my Label by using a hex code or an RGB value. Because of some reason, when doing so the background color always changes to white.

This works perfectly fine:

Label(
    title: { Text("someTitle") },
    icon: { Image(systemName: "someName") }
)
.background(Color.purple) // Using the provided standard Colors works perfectly fine.

However, I would like to create a background color using a hex or RGB value:

.background(Color(Color.RGBColorSpace.sRGB, red: 92, green: 225, blue: 230, opacity: 1))
// or
.background(Color(UIColor(red: 220, green: 24, blue: 311, alpha: 1)))

This does not work and the background color of the Label always changes back to white. How to achieve this goal?


Solution

  • The UIColor init method UIColor(red:green:blue:alpha) takes float values from 0 to 1 for each value.

    Any value ≥ 1.0 is going to "max out" that color. So an expression like UIColor(red: 220, green: 24, blue: 311, alpha: 1) will set all 3 color channels and alpha to 1.0, resulting in white. So would UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)

    You could create an extension to UIColor that adds convenience initializers that would take values of different types. First, and initializer that would take values from 0-255 for each. Then you could create another intializer UIColor.init(hexString:String).

    The one that took values from 0-255 would be a lot easier to write. The one that took hex strings would involve implementing a hex parser. I bet somebody has already written it though.

    Take a look at this code, for example:

    https://gist.github.com/anonymous/fd07ecf47591c9f9ed1a