实现方案:
TabView 外层嵌套 NavigationView,这样后续的View不用再使用NavigationView了,一个视图栈一个NavigationView
TabView
struct RootView: View {
@State var selection:Int = 0
init() {
// 设置选中和非选中文字颜色
let appearance = UITabBarAppearance()
appearance.stackedLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.blue]
appearance.stackedLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: UIColor.systemPink]
UITabBar.appearance().standardAppearance = appearance
UITabBar.appearance().scrollEdgeAppearance = appearance
}
var body: some View {
NavigationView {
TabView(selection: $selection) {
AView()
.tabItem {
Label(
title: { Text("A") },
icon: { Image(systemName: selection == 0 ? "book.pages.fill" : "book.pages") }
)
}
.tag(0)
DView()
.tabItem {
Label(
title: { Text("D") },
icon: { Image(systemName: selection == 1 ? "sun.rain.circle.fill" : "sun.rain.circle") }
)
}
.tag(1)
FView()
.tabItem {
Label(
title: { Text("F") },
icon: { Image(systemName: selection == 2 ? "moon.dust.circle.fill" : "moon.dust.circle") }
)
}
.tag(2)
}
}
}
}
#Preview {
RootView()
}
A
struct AView: View {
var body: some View {
NavigationLink {
BView()
} label: {
Text("打开B")
.font(.system(size: 30))
.foregroundColor(.white)
.frame(width: 200, height: 200)
.background(.red)
}
.navigationTitle("A")
}
}
B
struct BView: View {
@Environment(\.dismiss) private var dismiss
var body: some View {
NavigationLink {
CView()
} label: {
Text("打开C")
.font(.system(size: 30))
.foregroundColor(.white)
.frame(width: 200, height: 200)
.background(.red)
}
.navigationTitle("B")
.navigationBarBackButtonHidden()
.toolbar(content: {
ToolbarItem(placement: .topBarLeading) {
Button {
dismiss()
} label: {
Image(systemName: "arrowshape.turn.up.backward.fill")
.foregroundColor(.yellow)
}
}
})
}
}