如何使用 NavigationLink 在 SwiftUI 视图之间传递数据
How to pass data between SwiftUI views using NavigationLink
我正在进行一个小型 SwiftUI 练习,以学习如何使用 NavigationLink 在视图之间传递数据。我将 ContentView 设置为在点击 ContentView NavigationLink 后向 SecondView 发送消息。在 SecondView 中点击 NavigationLink 然后将消息发送到 ThirdView。但是,当我到达 ThirdView 时,我注意到一个奇怪的 UI 事件。请参阅下面的屏幕截图:
知道为什么会出现此 NavigationView 问题吗?是否与所有 3 个视图中都有 NavigationView 有关?
这是我的代码:
内容视图
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()
}
}
第二个视图
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())
}
}
第三视角
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())
}
}
欢迎提供反馈。谢谢!
删除第二个导航视图
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)")
}
}
我正在进行一个小型 SwiftUI 练习,以学习如何使用 NavigationLink 在视图之间传递数据。我将 ContentView 设置为在点击 ContentView NavigationLink 后向 SecondView 发送消息。在 SecondView 中点击 NavigationLink 然后将消息发送到 ThirdView。但是,当我到达 ThirdView 时,我注意到一个奇怪的 UI 事件。请参阅下面的屏幕截图:
知道为什么会出现此 NavigationView 问题吗?是否与所有 3 个视图中都有 NavigationView 有关?
这是我的代码:
内容视图
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()
}
}
第二个视图
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())
}
}
第三视角
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())
}
}
欢迎提供反馈。谢谢!
删除第二个导航视图
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)")
}
}