Sina
Sina

Reputation: 869

How to change body background color with if in SwiftUI

I'm creating a simple iOS app with SwiftUI, and I'd like to change my view's background color when switch toggle change. enter image description here

My code

struct ContentView: View {
    
    @State private var isOnLight: Bool = false
    
    var body: some View {
        
        VStack {
            Toggle(isOn: $isOnLight) {
                Text("Switch")
                    .font(.title)
                    .foregroundColor(.gray)
            }
            
            if isOnLight {
            }
        }.padding()
    }
}

Upvotes: 1

Views: 3306

Answers (2)

Javier Heisecke
Javier Heisecke

Reputation: 1222

For background colors you can use the ZStack like this and with one line ifs then decide on the color

struct ContentView: View {
    @State private var isOnLight: Bool = false
    
    var body: some View {
        ZStack {
            isOnLight ? Color.blue : Color.red
            VStack {
                Toggle(isOn: $isOnLight) {
                    Text("Switch")
                        .font(.title)
                        .foregroundColor(.gray)
                }
                
            }
            .padding()
        }
    }
}

To learn about how to use ternary operator in SwiftUI you can watch this video

Upvotes: 3

HunterLion
HunterLion

Reputation: 4006

You just need to embed your VStack inside a ZStack, where the back layer is a color that changes every time isOnLight changes.

Like this:

struct Example: View {
    
    @State private var isOnLight: Bool = false
    @State private var color: Color = .white
    
    var body: some View {
        ZStack {
            color
                .ignoresSafeArea()
            
            VStack {
                Toggle(isOn: $isOnLight) {
                    Text("Switch")
                        .font(.title)
                        .foregroundColor(.gray)
                }
            }
            .padding()
        }
        .onChange(of: isOnLight) { value in
            if value {
                color = .yellow
            } else {
                color = .white
            }
        }
    }
}

Upvotes: 1

Related Questions