NavigationStack & TabView
Hierarchical navigation (NavigationStack) combined with horizontal navigation (TabView)
Often, or perhaps always, we have a hierarchical navigation (NavigationStack) combined with horizontal navigation (TabView). Let’s see how to merge them:
struct ContentView: View {
var body: some View {
NavigationStack {
TabView {
Tab("Contacts", systemImage: "rectangle.stack.person.crop.fill") {
FirstView()
}
Tab("Chat", systemImage: "message.fill") {
SecondView()
}
}
}
}
}We have declared a NavigationStack that contains the TabView. Now, within any of the tabs, we can navigate forward and return.
Here is the FirstView:
struct FirstView: View {
var body: some View {
NavigationLink(destination: ThirdView()) {
HStack {
Image(systemName: "car")
.resizable()
.frame(width: 60, height: 60)
Text("Car")
}
}
}
}Instead, here is the ThirdView:
struct ThirdView: View {
var body: some View {
Text("In the third view")
.font(.largeTitle)
}
}To achieve this:
If, in the third view, we want to navigate to another view, we simply need to add another NavigationLink with the new destination.
A similar behavior occurs in the SecondView; for simplicity, we navigate to an EmptyView.
var body: some View {
VStack{
NavigationLink(destination: EmptyView()) {
HStack {
Image(systemName: "bus")
.resizable()
.frame(width: 60, height: 60)
Text("Bus")
}
}
}
}
}


