Adam Rush

@Adam9Rush

15 March, 2022

Introduction

You’re building another great SwiftUI application, and you’re likely to want to add multiple screens within your application. The best way to quickly achieve this is by adding a TabView. Like a UITabBar within the UIKit framework, it’s composed entirely for SwiftUI.

A TabView will allow you to switch between screens quickly and can be very useful for your users. Apple has started using the TabView more commonly in their applications. For example, if you use the Weather app or the Measurements app, you’ll see the TabView.

Adding a TabView

A TabView works by defining the object in the usual SwiftUI way.

You can go ahead and create a brand new SwiftUI project.

In your new SwiftUI View, go ahead and replace it with the following:

struct HomeView: View {
    var body: some View {
        TabView {
            HomeContentView()
                .tabItem {
                    Label("Home", systemImage: "person")
                }
            TransactionsView()
                .tabItem {
                    Label("Transactions", systemImage: "list.dash")
                }
        }
    }
}

In the above example, you’re creating a brand new TabView with two tabItems() that will control access to the following screens:

  • Home Screen
  • Transactions Screen

Adding a tabItem()

After the last curly brace, you will make two unique Views displayed for each above screen.

struct HomeContentView: View {
    var body: some View {
        Text("Home Content")
    }
}

struct TransactionsView: View {
    var body: some View {
        Text("Transactions")
    }
}

You have the HomeContentView and the TransactionsView displayed on each tab item. You can see this in the following code:

HomeContentView()
    .tabItem {
        Label("Home", systemImage: "person")
    }

Your incredible skill here is by utilising the Label object. You can, of course, use an Image and/or Text separately, but what’s fantastic is that you combine them both using a Label which will ensure alignment is handled for you.

You’re also taking advantage of SFSymbols, by defining the icon for each tab item. SF Symbols is a remarkable icon library provided by Apple, and you can have access to thousands of icons built right into the operating system.

What Next?

UITabBar provided by Apple in the early days of UIKit were super popular; in fact, most applications had them. Unfortunately, for some reason, they became unpopular again in the shift of the iOS design trends. However, with the birth of SwiftUI, TabBar’s are forever a popular choice, and you’ll see them recommended by Apple throughout the human guidelines.

They’re easy to integrate and super clean for users to interact with.

I am curious what you do next with this knowledge, let me know :]

Sponsor

Subscribe for curated Swift content for free

- weekly delivered.