Hi, I simply want to compare 2 values to determine the color of the background. I am unable to handle the if condition properly. If "tpsRealise" > "tpsEstime" background is red else is green. Thanks
struct ContentView: View {
@State var comparaisonTemps = true
@State var tpsRealise = 0
@State var tpsEstime = 0
var backgroundColor : Color {
return comparaisonTemps ? Color.green : Color.red
}
var body: some View {
ZStack {
backgroundColor
VStack {
Text("Tps Réalisé : \(tpsRealise)")
Image(systemName: "plus.square")
.font(.title)
.onTapGesture {
tpsRealise += 1
}
Spacer()
Text("Temps estimé : \(tpsEstime)")
Image(systemName: "plus.square")
.font(.title)
.onTapGesture {
tpsEstime += 1
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
It's because you've not told the view to update when something has changed. This works by setting the bgColour
to green initially, then it's recalculated when the icons are tapped. Because bgColour
is a @State
var and it's changed, the background is redrawn.
struct ContentView: View {
@State var bgColour = Color.green
@State var tpsRealise = 0
@State var tpsEstime = 0
var body: some View {
ZStack {
bgColour
VStack {
Text("Tps Réalisé : \(tpsRealise)")
Image(systemName: "plus.square")
.font(.title)
.onTapGesture {
tpsRealise += 1
bgColour = displayBackgroundColour()
}
Spacer()
Text("Temps estimé : \(tpsEstime)")
Image(systemName: "plus.square")
.font(.title)
.onTapGesture {
tpsEstime += 1
bgColour = displayBackgroundColour()
}
}
}
}
func displayBackgroundColour() -> Color {
return tpsRealise > tpsEstime ? Color.red : Color.green
}
}