我正在尝试将第一个 View 中的文本框的值传递到第二个 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()
}
}
所以,我真正想要的是第二个 View 中的文本框最初填充了传递的值。
我尝试了各种解决方案,但未能得到我需要的解决方案。如果我需要提供更多信息,请告诉我。
最佳答案
我们可以在onAppear
中将传入值设置为内部,例如
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 !!
使用 Xcode 13.4/iOS 15.5 进行测试
*(当然如果你不想分享它们,这还不清楚)
关于ios - 将值传递到导航链接 View 中的文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73004733/