Home > Enterprise >  Keep previous value for state var that will be change in the future
Keep previous value for state var that will be change in the future

Time:11-11

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?

CodePudding user response:

Updated 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's init(), but using a lifecycle event such as .onAppear.

struct TextFieldView: View {
    let initialName: String

    @State private var name: String
    
    var body: some View {
        TextField("Name", text: $name)
            .onAppear { self.name = initialName }
    }
}

CodePudding user response:

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 to name the value changes on each keystroke.

You could add a third @State property text and swap the values on submit

struct TextFieldView: View {
    @State private var text = ""
    @State private var name = ""
    @State private var oldName = ""
    
    var body: some View {
        VStack {
            TextField("Name", text: $text)
                .onSubmit {
                    oldName = name
                    name = current
                }
            Text(oldName)
        }
    }
}
  • Related