Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color rgb initializer not working as background in SwiftUI

Tags:

swift

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?

like image 730
LinusGeffarth Avatar asked Jun 04 '19 23:06

LinusGeffarth


People also ask

How do I add color in SwiftUI?

You need to create a new color by right-clicking anywhere in the list to open a menu, just click Color Set and you name the color however you want. Now open the Inspectors tab in the upper-right of your screen, you will see options that allow you to modify that color set.


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) 
like image 185
Michael St Clair Avatar answered Oct 02 '22 22:10

Michael St Clair


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) 
like image 24
Hernan Soberon Avatar answered Oct 02 '22 22:10

Hernan Soberon