How to create Tab Bar using TabView in SwiftUI

In UIKit, we use the UITabBarController to create the tab bar. While in SwiftUI we could use TabView instead.

To create a user interface with tabs, we place views in a TabView and apply the tabItem(_:) modifier to the contents of each tab.

Here is an example,

struct ProjectView: View {
    var body: some View {
        Text("Project View")
    }
}

struct StatisticView: View {
    var body: some View {
        Text("Statistic View")
    }
}

struct SettingsView: View {
    var body: some View {
        Text("Settings View")
    }
}

struct TabViewDemo: View {
    var body: some View {
        TabView {
            ProjectView()
                .tabItem {
                    Label("Projects", systemImage: "list.bullet")
                }
            
            StatisticView()
                .tabItem {
                    Label("Statistic", systemImage: "chart.pie.fill")
                }
            
            SettingsView()
                .tabItem {
                    Label("Settings", systemImage: "gearshape")
                }
        }
    }
}

As you can see, we create three custom views for the tabs and for each tab item we use a label, you could also use a Text or an Image instead.

The UI will be like below,

We could also assign a badge to each of the tabs. Let's say if we want to add notification badge for the Settings tab, we could do it like this,

SettingsView()
    .badge(2)
    .tabItem {
        Label("Settings", systemImage: "gearshape")
    }

Hope it helps,

Michael

DigitalOcean Referral Badge