skip to Main Content

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


  1. 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)
            }
        }
    }
    
    Login or Signup to reply.
  2. 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 }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search