I’m creating a simple iOS app with SwiftUI, and I’d like to change my view’s background color when switch toggle change.
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
For background colors you can use the ZStack like this and with one line ifs then decide on the color
To learn about how to use ternary operator in SwiftUI you can watch this video
You just need to embed your
VStack
inside aZStack
, where the back layer is a color that changes every timeisOnLight
changes.Like this: