SALE ENDS TODAY: Save 50% on all Swift books and bundles! >>

Adding TabView and tabItem()

Paul Hudson    @twostraws   

Fully updated for Xcode 11.2

When you want to show two separate views with SwiftUI, the easiest and most user-intuitive approach is with a tab bar across the bottom of our app. In our case, that means we’ll put our menu view in one tab and the active order in another. SwiftUI gives us a TabView for just this purpose, and it works much like a UITabBarController.

Press Cmd+N to create a new SwiftUI View, calling it “AppView”. Creating tabs is as easy as putting different views inside an instance of TabView, but in order to add an image and text to the tab bar item of each view we need to use the tabItem() modifier.

Let’s start with the code – change AppView to this:

struct AppView: View {
    var body: some View {
        TabView {
            ContentView()
                .tabItem {
                    Image(systemName: "list.dash")
                    Text("Menu")
                }

            OrderView()
                .tabItem {
                    Image(systemName: "square.and.pencil")
                    Text("Order")
                }
        }
    }
}

Let’s take a closer look at one of our views:

TabView {
    ContentView()
        .tabItem {
            Image(systemName: "list.dash")
            Text("Menu")
        }

That creates an instance of ContentView, and assigns a an image and text as its tab item label – the thing that represents this view in the tab bar. The image is created using the systemName initializer, which lets us load images from the built-in SF Symbols icon set.

To bring the tab bar to life we still need to do two more things. First, we need to add an Order instance into the preview environment so the OrderView can work:

struct AppView_Previews: PreviewProvider {
    static let order = Order()

    static var previews: some View {
        AppView().environmentObject(order)
    }
}

Second, we need to change SceneDelegate.swift so it creates an AppView rather than a ContentView. So, find this line:

let contentView = ContentView().environmentObject(order)

And replace it with this:

let contentView = AppView().environmentObject(order)

Now – at last! – you should be able to press Cmd+R to build and run your app, select some food, add it to your order, and see that information appear in the Order tab automatically.

What I love about this approach is that we’re not doing the real heavy lifting of making different parts of our UI sync up – the ObservableObject protocol and @EnvironmentObject attribute are making sure all parts of our UI stay up to date. So, as soon as the ItemDetail screen announces that something has been added to the order, the OrderView screen will automatically refresh to show the changes.

In the background, any view that relies on an environment object will be refreshed when it announces changes. In practice that means SwiftUI will re-invoke the body property, which in turn means everything inside body will read the latest values from the environment.

Further reading

SPONSORED Instabug helps you identify and resolve severe crashes quickly. You can retrace in-app events and know exactly which line of code caused the crash along with environment details, network logs, repro steps, and the session profiler. Ask more questions or keep users up-to-date with in-app replies straight from your dashboard. Instabug takes data privacy seriously, so no one sees your data but you! See more detailed features comparison and try Instabug's crash reporting SDK for free.

Save 50% on all books and bundles

The biggest ever Hacking with Swift sale is now on, letting you save 50% on all books and bundles. Learn something new with Swift and enjoy great savings while the sale lasts!

Click here to save 50% in our Black Friday sale!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5