skip to Main Content

I’m new to swiftUI here and I want to try out to pass data between two views. But it doesn’t seem to work.

I’m using Xcode 13.2 & iOS 15 for the simulator.

This is my code for the first view:

struct ContentView: View {
    @State var myName: String = ""

    var body: some View {
            
        NavigationView {
            VStack {
                    
                TextField("Enter your name", text: $myName)
                
                Text(self.myName)
                
                NavigationLink(destination: BView(myName: self.$myName), label: {
                    Image(systemName: "arrowshape.turn.up.left")
                })
                
            }//: VSTACK
            .padding(.horizontal, 20)
        }//:NAVIGATION VIEW
        
    }
        

    }

This is code for the second view:

struct BView: View {
    @Binding var myName: String
    
    var body: some View {
        NavigationView {
            Text("BView")
            Text(self.myName)
            
        }//:NAVIGATION VIEW
    }
}

I want myName to be input in the first page which is ContentView() and then pass down the input data to BView().

Unfortunately, once I run it on the simulator, the input data doesn’t;t show up.

2

Answers


  1. Your code is fine just add VStack in BView.

    struct BView: View {
        @Binding var myName: String
        
        var body: some View {
            NavigationView {
                VStack { // HERE
                    Text("BView")
                    Text(self.myName)
                }
                
            }//:NAVIGATION VIEW
        }
    }
    
    Login or Signup to reply.
  2. Please use @EnvironmentObject to pass the data to view.
    https://developer.apple.com/documentation/swiftui/environmentobject

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search