Is it possible to store previous state in a swiftUI view, and if so, how?
I have a view that can take an optional value as an input. If this value is nil, then I would like the view to change color (to show something is wrong) and show the previous valid value it had.
Below is an example showing what I hope to achieve.
The IntView takes an optional Int as an input. It will show "Not a int." in red if it is nil, but in that case, I would like to show the previous valid value, but in red.
In the example given, I have a simple ContentView with a TextField in which you can type an int value. The conversion of string to Int (on line 4) will return nil if the string typed in the TextField is not a valid integer.
I've tried doing it with state in my IntView but I cannot update the state when the body is computed.
struct ContentView: View {
@State var intAsString: String = ""
var body: some View {
let intValue = Int(intAsString)
return VStack {
IntView(value: intValue)
TextField("", text: $intAsString)
}
}
}
struct IntView: View {
var value: Int?
var body: some View {
let foreColor: Color
let text: String
if value == nil {
foreColor = Color.red
text = "Not a int."
} else {
foreColor = Color.primary
text = "\(value!)"
}
return Text(text).foregroundColor(foreColor)
}
}