Home > Software engineering >  Pass value in TextField to other view
Pass value in TextField to other view

Time:11-14

so I've just got simple code with TextField and just print textfield in the same view. I want to pass typed text to another View - it's not working currently and I don't know why.

Here is my first view code:

import SwiftUI
import UIKit

struct Test: View {
    @State private var username: String = ""
    var body: some View {

        
        TextField(
            "Your name",
            text: $username
        )
        
        Text("hello, \(username)")
            .foregroundColor(.black)
        
        NavigationLink(destination: OtherView()){
            
            Text("GO TO OTHER VIEW")
                .frame(width: 280, height: 70)
            
        }
    
    }
}

And here is my other view.

struct OtherView : View {
    @State private var username: String = ""
 
    var body: some View {
            
           VStack {  
                        Text("hello, \(username)!")
                            .foregroundColor(.white)
                            .font(.headline)
                            .padding(30)
}
}
}

I doń't have any idea how can I make it possible to print typed text in other view.

CodePudding user response:

Right now, you have two completely separate username variables. One is owned by Test and the other is owned by OtherView -- they have no connection to each other (giving them the same name does not make them the same).

If you want to pass the value from the first View to the second, you can make it a parameter that gets passed into the second View.

That parameter doesn't need to be @State on the second View, since it's not mutated at all.

struct Test: View {
    @State private var username: String = ""
    var body: some View {

        NavigationView {
            VStack {
                TextField("Your name", text: $username)
                Text("hello, \(username)")
                    .foregroundColor(.black)
                NavigationLink(destination: OtherView(username: username)){
                    Text("GO TO OTHER VIEW")
                }
            }
        }
        
    
    }
}

struct OtherView : View {
    var username: String
    
    var body: some View {
        VStack {
            Text("hello, \(username)!")
        }
    }
}

Note that I've included what's necessary to create a minimal reproducible example, like having a NavigationView that you may not need in your original project if there's additional context there not included in the question.

  • Related