03 Jul, 2019

SwiftUI TabbedView in Xcode 11 Beta 3

SwiftUI TabbedView in Xcode 11 Beta 3

In a previous article we had outlined the basics of the setup of a TabbedView in SwiftUI. Unfortunately, at the moment of writing Xcode was in Beta 2 and the API for this component was not yet complete.

As a review, let's have a look again at the setup briefly showcased in the WWDC19 session 216 SwiftUI Essentials.

In the session tabItemLabel is used to specify the tab items of the TabbedView. This was the particular part of the setup that was problematic back in Xcode11 Beta 2.

A quick look at the iOS & iPadOS 13 Beta 3 Release notes confirms that this issue has been addressed:

The tabItemLabel(_:) modifier — now named tabItem(_:) — now accepts @ViewBuilder closures. (51502668)

The code presented at WWDC used tabItemLabel(_:) and not tabItem(_:). This naming change seems much more adequate to describe the element in question.

So, what were the Apple engineers using in their demo back in June? Such is the world of Beta software.

Whatever the case, it is very cool to finally see a more mature version of this API and without further delays let's get building our first SwiftUI TabbedView.

The new API on tabItem(_:) works as promised. We can specify an Image and a Label inside its closure to create what on UIKit would be a UITabBarItem.

Note that even though we specified the Label first and the Image second (bellow it), SwiftUI still composes the tabItem with the Image first and the Label bellow. So, the order of the elements inside doesn't really matter as long as these are either Text or Image or both.

In the same way, attempting to place more than one Image results in only the first instance getting used and the rest ignored.

How about placing other random elements inside, like say, HStack?

Same result. HStack is completely ignored and only the Image and Text inside get drawn. I've also tried putting a Toggle, a Button, another TabbedView. They all yield similar results.

That is some serious leniency(?) built in to the API. I don't even get a warning in the console.

TabbedView in iPadOS

If we take our minimum TabbedView setup and run it on the iPad simulator we will encounter a difference with the version we see on iOS. The Image and Text inside each tab item are laid out next to each other rather than one bellow the other. Any attempts at using a VStack to specify that the views inside the tab item be laid out differently are once again ignored.

alt text

Sample project

You can find a finalized sample project at https://github.com/piterwilson/MyTabbedView

Sources and Further reading