简体   繁体   中英

How to pass data between SwiftUI views using NavigationLink

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:

在此处输入图片说明

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!

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)")
        }
    
}
    


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM