Search code examples
swiftswiftuibackground-color

Set custom background color on a stack in Swift (SwiftUI)


My code currently consists of:

VStack{
   Text("Something")
}
.background(Color.red)

I want to use a custom color for the background instead of Color.red. However, looking at the documentation, it seems like the background function takes in a background. Therefore, I can't declare a variable:

let exampleColor : Color = Color(red: 141, green: 223, blue: 144)

and use it within the background function. How do I tackle this problem?

VStack{
   Text("Something")
}
.background(exampleColor)

Doesn't work.


Solution

  • You have to set values between 0 to 1 for RGB Colors. Use the following

    let exampleColor : Color = Color(red: 141/255, green: 223/255, blue: 144/255)
    

    or value between 0 to 1 like

    let exampleColor : Color = Color(red: 0.5, green: 0.8, blue: 0.5)