SwiftUI Blog

Mastering SwiftUI: Your Guide to Building Beautiful, Intuitive Apps.

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

2 responses to “NavigationStack & TabView”

  1. JMC Avatar
    JMC

    But I couldn’t set the nav title and nav item inside FirstView(). What’s the solution?

    1. NICOLA.DEFILIPPO Avatar
      NICOLA.DEFILIPPO

      Why do you have to show the title in the FirstView? It’s not make sense, the title of the tab item says at the user where he is. Anyway, if you need it, i think something like this (hope that can help)
      FirstView()
      .toolbar {
      ToolbarItem(placement: .principal) {
      Text("ciao")
      .font(.largeTitle)
      }
      }