I have multiple @State var that will be changed in the TextField, but I want to keep the old values to be used after the state values are changed on the TextFields
@State var name: String
var oldName = ???
What is the best approach for this?
I have multiple @State var that will be changed in the TextField, but I want to keep the old values to be used after the state values are changed on the TextFields
@State var name: String
var oldName = ???
What is the best approach for this?
2
Answers
If you want to keep the entire string of the old value you have to implement the
.onSubmit
modifier because if the text field is bound toname
the value changes on each keystroke.You could add a third
@State
propertytext
and swap the values on submitUpdated to remember the initial name, not the previous name.
If you want to remember the initial name, it will have to be supplied by a parent view as regular constant. This way, it is decoupled from the modifiable state property that the
TextField
operates on. The only thing missing, now, is that the textfield needs to be pre-filled with the initial name. This can’t (shouldn’t) be done in the view’sinit()
, but using a lifecycle event such as.onAppear
.