Hi! I find this code does not work as expected on iOS 17 simulator and device. It was working correctly with iOS 16:
struct ContentView: View {
@State private var numberText = ""
var color: Color {
let result = (Int(numberText) ?? 0) <= 0
if result {
return .black
}
return .red
}
var body: some View {
VStack {
TextField("Enter a number", text: $numberText)
.font(.title)
.foregroundStyle(
color
)
Text("Font color will turn red if number > 0")
.foregroundColor(.gray)
}
.padding()
}
}
I tried a workaround and it works:
struct ContentView: View {
@State private var numberText = ""
@State private var color = Color.black
func updateColor() ->Color {
let result = (Int(numberText) ?? 0) <= 0
if result {
return .black
}
return .red
}
var body: some View {
VStack {
TextField("Enter a number", text: $numberText)
.font(.title)
.foregroundStyle(
color
)
.onChange(of:numberText) {
color = updateColor()
}
Text("Font color will turn red if number > 0")
.foregroundColor(.gray)
}
.padding()
}
}