在 TabView 中添加 NavigationView 时,我会从堆栈中的任何视图中获得 pop-to-root 情况。
当然,预期的行为是每个视图都回退到前一个,直到我们到达 Root (Home)
(有一个功能性的解决方法,但我不太喜欢。)
所以我真的希望有人能指出原因,以及问题的可能解决方案。
这里是整个场景的精简代码示例。
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
NavigationView{ HomeView() }
.tabItem { Image(systemName: "house"); Text("Home") }
Text("Left").font(.title).fontWeight(.heavy)
.tabItem { Image(systemName: "chevron.left.square"); Text("Left") }
Text("Up").font(.title).fontWeight(.heavy)
.tabItem { Image(systemName: "chevron.up.square"); Text("Up") }
Text("Right").font(.title).fontWeight(.heavy)
.tabItem { Image(systemName: "chevron.right.square"); Text("Right") }
}
}
}
struct HomeView: View {
var body: some View {
Text("Home").font(.title).fontWeight(.heavy)
.navigationBarTitle("Home")
.navigationBarItems(trailing: NavigationLink(destination: NavChild1(), label: { Text("GoTo 1 >") }))
}
}
struct NavChild1: View {
var body: some View {
Text("Nav1").font(.title).foregroundColor(.white).background(Color.red)
.navigationBarTitle("Nav 1")
.navigationBarItems(trailing: NavigationLink(destination: NavChild2(), label: { Text("GoTo 2 >") }))
}
}
struct NavChild2: View {
var body: some View {
Text("Nav2").font(.title).foregroundColor(.white).background(Color.green)
.navigationTitle("Nav 2")
.navigationBarItems(trailing: NavigationLink(destination: NavChild3(), label: { Text("GoTo 3 >") }))
}
}
struct NavChild3: View {
var body: some View {
Text("Nav3").font(.title).foregroundColor(.white).background(Color.blue)
.navigationTitle("Nav 3")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
答案 0 :(得分:1)
NavigationLink 似乎不适用于 .navigationBarItems(trailing:)
。
相反,您可以使用 toolbar
并添加带有 ToolbarItem
展示位置的 .navigationBarTrailing
:
struct HomeView: View {
var body: some View {
Text("Home").font(.title).fontWeight(.heavy)
.navigationTitle("Home")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
NavigationLink(destination: NavChild1(), label: { Text("GoTo 1 >") })
}
}
}
}
然后对其余链接执行相同操作:
struct NavChild1: View {
var body: some View {
Text("Nav1").font(.title).foregroundColor(.white).background(Color.red)
.navigationTitle("Nav 1")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
NavigationLink(destination: NavChild2(), label: { Text("GoTo 2 >") })
}
}
}
}
struct NavChild2: View {
var body: some View {
Text("Nav2").font(.title).foregroundColor(.white).background(Color.green)
.navigationTitle("Nav 2")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
NavigationLink(destination: NavChild3(), label: { Text("GoTo 3 >") })
}
}
}
}