Color rgb initializer not working as background in SwiftUI

Viewed 25034

I'm trying to set a button's background color to some custom rgb value. I create the button as follows:

Button(action: {
    print("tapped")
}) {
    Text("Let's go")
}
    .background(Color.black)

This works fine, and the button's background is, in fact, black. However, when initializing the background color like this, it does not work and there's just no background color at all:

.background(Color(red: 242, green: 242, blue: 242))

Why is that?

2 Answers

It looks like it is asking for the colors in percentages, I was able to get it to work doing this

Color(red: 242 / 255, green: 242 / 255, blue: 242 / 255)

The Color expects 3 Double values from 0.0 to 1.0 for each tone. If you pass this...

WRONG:

.background(Color(red: 242, green: 242, blue: 242))

It is converted to WHITE since all values are bigger than 1.

To fix this you could divide each value by 255 and get your hex conversion (as the 1 Answer)

CORRECT:

Color(red: 242 / 255, green: 242 / 255, blue: 242 / 255)
Related