Create a Tab View in SwiftUI
Written by Team Kodeco
Tab views are a great way to organize content and navigation options in your app. In SwiftUI, creating a tab view is straightforward using TabView
.
Each tab within a TabView
is a TabItem
. Each TabItem
should have a unique tag value, and should contain the content that you want displayed when that tab is selected.
Here’s an example with two tabs:
struct ContentView: View {
var body: some View {
TabView {
Text("Tab 1's a star!")
.tabItem {
Image(systemName: "star")
Text("Tab 1")
}.tag(1)
Text("Show the love for Tab 2!")
.tabItem {
Image(systemName: "heart")
Text("Tab 2")
}.tag(2)
}
}
}
Your preview should look like this:
In the above example, each TabItem
contains an Image
and Text
view. The Image view displays an icon in the tab, while the Text view displays the title of the tab. The .tag(1)
and .tag(2)
modifiers set a unique identifier for each TabItem
.
You can add as many tabs as you’d like to the TabView
and customize their appearance in various ways. Once you’ve added all your tabs and configured them to your liking, you can present the TabView
using a NavigationView
or other view in your app.
That’s it! With just a few lines of SwiftUI code, you can create a tab view in your app to easily navigate between multiple screens.