Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

462
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!