In this tutorial, I am going to let you know how to change the background color in SwiftUI by clicking a button. We will make the height of a VStack full using the Spacer()
to set it for the entire screen. Inside the VStack
, we will have our code.
Before we go discussing this further let’s look at the complete code below:
@State var vstackColor: Color? = .green
var body: some View {
VStack {
Text("Welcome to SwiftSpeedy")
Divider()
Button(action: {
vstackColor = .red
}, label: {
Text("Change Background Color")
})
Spacer()
}
.background(vstackColor ?? Color.green)
}
In the above code, we have VStack in the view and there is also a button. tapping the SwiftUI button will change the background color of our VStack
.
In our code, we have first created a variable with @State property that holds the color:
@State var vstackColor: Color? = .green
After that, we added this color variable in VStack to apply the color as the background color of VStack. In our case, it is green.
Next, we created a button. Inside the button action, we have changed the color variable to red
. Thus, when we tap the button, it will change the color of the color variable and ultimately change the background color of SwiftUI VStack.
This is happening because we have set the vstackColor
variable as the background color of VStack
.
When we start the app, it will show the background color green because we have set it green in the variable vstackColor
and applied it to the background color of VStack. After we tap the button, the color will change from green
to red
as we are storing the color red as the variable value in the action.
Note: If you wish, you can also use HStack or ZStack and set it for the entire screen. In the same way we did using VStack, you can also change the background color for HStack and ZStack.