Home > Enterprise >  How to pass data between SwiftUI views using NavigationLink
How to pass data between SwiftUI views using NavigationLink

Time:11-14

I am engaging in a small SwiftUI exercise to learn how to pass data between views using NavigationLink. I set up ContentView to send a message to the SecondView after tapping the ContentView NavigationLink. Tapping NavigationLink in the SecondView then sends the message to the ThirdView. However, I am noticing a strange UI occurrence by the time I get to ThirdView. See the screenshot below:

enter image description here

Any idea why this NavigationView issue is occurring? Is it related to having NavigationView in all 3 views?

Here is my code:

ContentView

struct ContentView: View {
    var body: some View {
        
        NavigationView {
            NavigationLink(destination: SecondView(message: "Hello from ContentView")) {
                Text("Go to Second View")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

SecondView

struct SecondView: View {
    var message: String
    
    var body: some View {
        Text("\(message)")
        
        NavigationView {
            NavigationLink(destination: ThirdView(message: self.message)) {
                Text("Go to Third View")
            }
        }
    }
}

struct SecondView_Previews: PreviewProvider {
    static var previews: some View {
        SecondView(message: String())
    }
}

ThirdView

struct ThirdView: View {
    var message: String
    
    var body: some View {
        NavigationView {
            Text("\(message)")
        }
    }
}

struct ThirdView_Previews: PreviewProvider {
    static var previews: some View {
        ThirdView(message: String())
    }
}

Feedback is appreciated. Thanks!

CodePudding user response:

remove the second navigation view

struct SecondView: View {
    var message: String
    var body: some View {
        VStack(spacing: 100 ) {
            Text("\(message)")
            NavigationLink(destination: ThirdView(message: self.message)) {
                Text("Go to Third View")
            }
        }    
    }
}




struct ThirdView: View {
    var message: String
    
    var body: some View {

            Text("\(message)")
        }
    
}
    


  • Related