Maz haz issue with conditionals:
I am trying to add a conditional modifier to make my "Total Amount" text red when the 0% tip is selected
I like to think of @State
variables as lights on a car's dashboard. You can easily tell if the petrol, high beams, or boot open lights are on or off. Maybe you do something when all the lights are off? Maybe you do something else when just the petrol light is on? The state of the lights trigger certain driver actions. Now transfer that thinking to your View
.
You probably have an @State
variable for your tip amount. I don't see it, but you do have an @State
variable for tip percentage.
Picker("Tip Percentage", selection: $tipPercentage) { // <-- I see you have an @State here
ForEach(0..<101) { number in
Text(number, format: .percent)
}
} .pickerStyle(.navigationLink)
} header: {
Text("How much tip do you want to leave?")
}
Is the light on? or off?
You have the variable $tipPercentage
that will be some number from zero to 100. So think of this as a light bulb in your view. If the value is ZERO, think to yourself that the cheapskate light is ON.
This is SwiftUI. You DECLARE what you want to see when the LIGHT IS ON.
So consider defining a computed variable that returns a tip percentage color. If the tip percentage is ZERO, return a red color, otherwise return an indigo color.
// Computed properties are great for declaring your intentions!
var tipPercentageColor: Color {
tipPercentage == 0 ? .red : .indigo
// This is short hand for IF the tipPercentage is ZERO, then return Color.red. Otherwise return Color.indigo
}
Now, with this computed variable you can just DECLARE what you want this Text()
view to display.
Text(totalAmount, format: currency)
.foregroundColor( tipPercentageColor ) // <-- Use your computed variable here
Whenever $tipPercentage
changes, the computed variable will recalculate!
You simply tell the Text()
field displaying your totalAmount
to always have the color tipPercentageColor
.
Keep Coding!
Please return here and let us know how you solved this!