4

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
christophriepe
  • 1,157
  • 12
  • 47
  • 1
    `Color(UIColor(red: 220/255, green: 24/255, blue: 311/255, alpha: 1)` – Leo Dabus Sep 30 '20 at 18:00
  • Leo Dabus provides an answer that worked for me, because it is in Swift! The main answer in "how to create a UIColor" is how to #define a macro to do this, but ... this doesn't work inSwift! :-) Thanks, Leo! – George D Girton Aug 04 '22 at 14:47

1 Answers1

3

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

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • 1
    This should be closed as duplicate. Btw perfect timing with my comment. Same second – Leo Dabus Sep 30 '20 at 18:00
  • Note: **On applications linked for iOS 10 or later, the color is specified in an extended color space, and the input value is never clamped.** Of course that for such high values it would make it always return white – Leo Dabus Sep 30 '20 at 18:04