SwiftUI Tab View Tutorial

In SwiftUI Tab Views are used to display a view when the tab items are selected. The tab items will contain a Text View and an Image. In this tutorial two tab items will be created with the containing views.. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUITabViewTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

Create a new file to the project. Choose File -> New -> File and select iOS -> User Interface -> Swift View and enter HomeView as the filename. Change the HomeView struct in

struct HomeView: View {
    var body: some View {
        ZStack {
            Color.red
            .edgesIgnoringSafeArea(.all)
            Text("Home View")
                .font(.largeTitle)
        }
    }
}

This will change the background color to red and set the text to “Home View”. Next, add another file and give it a name of AboutView. Change the AboutView Struct in

struct AboutView: View {
    var body: some View {
        ZStack {
            Color.blue
                .edgesIgnoringSafeArea(.all)
            Text("About View")
                .font(.largeTitle)
        }
    }
}

In the Project navigator, click to select ContentView.swift. In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

Change the code inside the ContentView struct to

struct ContentView: View {
    var body: some View {
        // 1
        TabView {
            // 2
            HomeView()
                // 3
                .tabItem {
                    VStack {
                        Image(systemName: "1.circle")
                        Text("Home")
                    }
            // 4
            }.tag(1)
            
            // 5
            AboutView()
                .tabItem {
                    VStack {
                        Image(systemName: "2.circle")
                        Text("About")
                    }
            }.tag(2)
        }
    }
}
  1. Tab View will contain the views and the corresponding tab items.

  2. The HomeView will be displayed when the first tab item is selected

  3. The tab item contains a Text view and an image view

  4. The tag identifier can be used to display the view programmatically.

  5. The AboutView will be displayed when the second tab is selected.

The preview will look like this.

The source code of the SwiftUITabViewTutorial can be downloaded at the ioscreator repository on Github.