Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

468
Vistas
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()
    }
}
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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

over 4 years ago · Santiago Trujillo Denunciar

0

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
            }
        }
    }
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda