Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add a Tab View to Navigation View in SwiftUI
Written by Team Kodeco

When building an app with SwiftUI, you may want to include a tab view within a navigation view. This can be helpful when you want to display different categories of content within a single screen.

To add a tab view to a navigation view, you can simply embed the tab view in a navigation view using the NavigationStack and TabView structs.

Here’s an example implementation:

struct ContentView: View {
  var body: some View {
    NavigationStack {
      TabView {
        Text("First Tab")
          .tabItem {
            Image(systemName: "house")
            Text("Home")
          }
        
        Text("Second Tab")
          .tabItem {
            Image(systemName: "person")
            Text("Profile")
          }
      }
      .navigationTitle("My App")
    }
  }
}

Your preview should look like this:

Tab views can easily be embedded in navigation views.
Tab views can easily be embedded in navigation views.

In the example above, you create a tab view with two tabs. Each tab includes a view with some simple text content, as well as an icon and label specified using the tabItem modifier.

You then embed the tab view in a navigation view and set the title of the navigation bar using the navigationTitle modifier.

To include more tabs or customize the appearance of the tabs or navigation view, you can modify the contents of the TabView and NavigationView structs using the same principles as described in the previous cookbook entries.

Overall, adding a tab view to a navigation view in SwiftUI is a straightforward process that can help you create a more streamlined and cohesive user experience in your app.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.