Home > Blockchain >  How to change body background color with if in SwiftUI
How to change body background color with if in SwiftUI

Time:02-26

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()
    }
}

CodePudding user response:

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

CodePudding user response:

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
            }
        }
    }
}
  • Related