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:
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.