skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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
                }
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search