LinusG.
LinusG.

Reputation: 28892

Color rgb initializer not working as background in SwiftUI

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?

Upvotes: 44

Views: 37167

Answers (3)

Guilherme Carvalho
Guilherme Carvalho

Reputation: 330

I wrote a simple but helpful extension based on Michael's answer

public extension Color {
    static func fromRGB(red: Double, green: Double, blue: Double, opacity: Double = 255) -> Color {
    Color(red: red/255, green: green/255, blue: blue/255, opacity: opacity/255)
  }
}

Upvotes: 2

Hernan Soberon
Hernan Soberon

Reputation: 171

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)

Upvotes: 17

Michael St Clair
Michael St Clair

Reputation: 6605

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)

Upvotes: 115

Related Questions