Search code examples
iosswiftuinavigationview

Passing a value to a text box in navigation link view


I am trying to pass a value from a text box in my first view to a text box in my second view.

struct FirstView: View {
@State private var inputTextValue = ""
var body: some View {        
    NavigationView{
        VStack {
            TextField("",text: $inputTextValue)
                .frame(width: 200, height: 30, alignment: .center)
                .border(.gray)
            NavigationLink(destination: {SecondView(incomingTextFieldvalue: inputTextValue)}, label: {Text("To second view")})
        }
    }
}


struct SecondView: View {
var incomingTextFieldvalue: String
@State var textFieldValue = "Initial Value in view 2"
var body: some View {
    VStack {
        Spacer()
        TextField("",text: $textFieldValue)
            .frame(width: 200, height: 30, alignment: .center)
            .border(.gray)
        Spacer()
        Text("Incoming value: \(incomingTextFieldvalue)")
        Text("This value: \(textFieldValue)")
        
        Spacer()
    }
}

So, what I want exactly is that the text box in the second view has the passed value filled in initially.

I have tried various solutions, but have not been able to get the solution that I need. Please let me know if I need to provide more info.


Solution

  • We can set incoming value to internal in onAppear, like

    VStack {
        Spacer()
        TextField("",text: $textFieldValue)
            .frame(width: 200, height: 30, alignment: .center)
            .border(.gray)
        Spacer()
        Text("Incoming value: \(incomingTextFieldvalue)")
        Text("This value: \(textFieldValue)")
    
        Spacer()
    }
    .onAppear { textFieldValue = incomingTextFieldvalue }   // << here !!
    

    Tested with Xcode 13.4 / iOS 15.5

    *(of course if you don't want to share them, which is unclear)