Skip to content

Tabs (SwiftUI)


Prepared and tested with Xcode 13.3.1 and Swift 5.3 (last update: 2022-05-20)

In this part you will learn about the tabs, probably the simplest method allowing you to move between different child views. You do this very intuitively either by selecting tab items located in a tab bar or, when using the page view tab style, by swiping.

Table of contents


Project

  • Step 1: create project
    Create a new iOS project, as you did in Start Xcode and set up a project section of First application (SwiftUI) part and name it SwiftUI iOS TabView:

  • Step 2: create tab "frame"
    Open in editor the ContentView.swift and in ContentView structure replace default Text with TabView:

    You will see an empty screen with gray area at the bottom of the screen reserved for tabs:

  • Step 3: add views – each view defines one tab
    Inside TabView add three views – you can add any view you want, even very complicated but to keep this example simple now you add three Text views:

    You will see a screen with text First tab but without tabs area at the bottom:

    Reason for this is that now you have a choice how you will interact with tabs: you can use typical tabs or instead use swiping.

  • Step 4: use tab bar to select view
    Create tab bar items by applying a tabItem() modifier:

  • Step 5: select tab in code
    To control the currently selected tab in code, a you have to add tag to each tab item:

  • Step 6: use swiping to select view
    For swiping you need only views and tabViewStyle() modifier:


Summary

You have learned probably the simplest method to organize multiple views.

The key points of this part are:

  • How to use TabView to "switch" between multiple views.
  • How to implement tab bar with tabs located along the bottom edge of the screen.
  • How to replace tabs with swiping.