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.
CodePudding user response:
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)
CodePudding user response:
You need to use @Binding
like so:
In FirstView:
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")})
}
}
}
}
In SecondView:
struct SecondView: View {
@State var textFieldValue = "Initial Value in view 2"
@Binding var incomingTextFieldvalue: String
var body: some View {
VStack {
Spacer()
TextField("",text: $incomingTextFieldvalue)
.frame(width: 200, height: 30, alignment: .center)
.border(.gray)
Spacer()
Text("Incoming value: \(incomingTextFieldvalue)")
Text("This value: \(textFieldValue)")
Spacer()
}
}
}
Also note that when passing a destination
for the NavigationLink
you don't need to use {}