简体   繁体   English

如何使用 NavigationLink 在 SwiftUI 视图之间传递数据

[英]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.我正在进行一个小型 SwiftUI 练习,以了解如何使用 NavigationLink 在视图之间传递数据。 I set up ContentView to send a message to the SecondView after tapping the ContentView NavigationLink.我将 ContentView 设置为在点击 ContentView NavigationLink 后向 SecondView 发送消息。 Tapping NavigationLink in the SecondView then sends the message to the ThirdView.在 SecondView 中点击 NavigationLink,然后将消息发送到 ThirdView。 However, I am noticing a strange UI occurrence by the time I get to ThirdView.但是,当我到达 ThirdView 时,我注意到出现了一个奇怪的 UI。 See the screenshot below:请看下面的截图:

在此处输入图片说明

Any idea why this NavigationView issue is occurring?知道为什么会出现这个 NavigationView 问题吗? Is it related to having NavigationView in all 3 views?它与在所有 3 个视图中都有 NavigationView 相关吗?

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


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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