Reputation: 1076
According to this tutorial: https://www.simpleswiftguide.com/swiftui-textfield-complete-tutorial/ whenever you pass in the input to the TextField, it "is saved" in the variable that you add to the TextField. How to pass the new value between the classes then?
The code:
import SwiftUI
struct ContentView: View {
@State var input: String = ""
var body: some View {
NavigationView{
VStack {
Text("Enter your text here:")
TextField("Enter Text", text:$input)
.multilineTextAlignment(.center)
NavigationLink(destination:FinalView()){
Text("Run")
}
}
}
}
}
struct FinalView: View {
var body: some View {
Text(ContentView().input)
}
}
I don't get any errors and it runs smoothly, but there is no output in the FinalView()
(the sheet is blank).
This is just an minimal viable version of a problem I encountered in much more complicated app, so please don't look for a walk-around, rather help me look for the exact answer or prove it's not viable at all. Thanks!
Upvotes: 1
Views: 708
Reputation: 52565
If FinalView
doesn't need to mutate the variable, then you can just pass it as a parameter:
struct ContentView: View {
@State var input: String = ""
var body: some View {
NavigationView{
VStack {
Text("Enter your text here:")
TextField("Enter Text", text:$input)
.multilineTextAlignment(.center)
NavigationLink(destination:
FinalView(input: input)
){
Text("Run")
}
}
}
}
}
struct FinalView: View {
var input : String
var body: some View {
Text(input)
}
}
If you need two-way communication (eg the child view needs to mutate the variable), you can use a @Binding
:
struct ContentView: View {
@State var input: String = ""
var body: some View {
NavigationView{
VStack {
Text("Enter your text here:")
TextField("Enter Text", text:$input)
.multilineTextAlignment(.center)
NavigationLink(destination:
FinalView(input: $input)
){
Text("Run")
}
}
}
}
}
struct FinalView: View {
@Binding var input : String
var body: some View {
TextField("", text: $input)
}
}
Note that trying to reach into the parent view (ContentView().input
) will not work -- that creates a new instance of ContentView
and is not the same input
you're expecting.
Unrelated side note: you should only have one NavigationView
in your hierarchy -- I've removed the one in FinalView
Upvotes: 2