tezvyn:

TabView: SwiftUI's Built-in Tab Bar

AI-drafted, machine-checkedSource: developer.apple.combeginner
TabView: SwiftUI's Built-in Tab Bar

TabView lets you show different views in the same space, switched by a tab bar. It's the standard for top-level app navigation, like switching between "Home," "Search," and "Profile." The footgun is nesting them; they are for main sections only.

WHY IT EXISTS: Apps often need to present a few distinct, equally important sections of content. Instead of forcing users back to a main menu, a tab bar provides persistent, one-tap access to these core areas. TabView is SwiftUI's declarative component for this common UI pattern.

THE MENTAL MODEL: Think of TabView as a container holding a stack of cards, where only one card is visible at a time. The tab bar at the bottom is the set of buttons that chooses which card to show. Each tab is independent and typically maintains its own state and navigation stack.

HOW IT WORKS: You create a TabView and place your different content views directly inside it. For each view that should have a corresponding tab in the bar, you attach the .tabItem modifier. Inside this modifier's closure, you define the tab's appearance, usually an Image (like an SF Symbol) and a Text label. SwiftUI automatically handles the user interaction, switching the visible view when a tab is tapped. To control the selection programmatically, you can bind the TabView's selection to a state variable.

WHEN TO USE IT: Use TabView for the primary, top-level navigation of an app. It is ideal when you have between two and five main sections that a user might want to switch between frequently and without losing their place in any given section. Common examples include social media, banking, and music apps.

WHEN NOT TO USE IT: Avoid TabView for secondary navigation, like filtering a list or showing steps in a multi-part form. For those cases, components like Picker or a SegmentedControl are more appropriate. Also, do not use a TabView if you have more than five main sections, as the tab bar becomes too crowded. In that scenario, one of the tabs often becomes a "More" tab that leads to a list of the remaining sections.

ONE CANONICAL EXAMPLE: A basic social media app could use a TabView to manage its main screens. It would contain a HomeFeedView with a .tabItem showing a "house" icon and "Home" text. Next, a SearchView with a .tabItem for a "magnifyingglass" icon and "Search" text. Finally, a ProfileView with a .tabItem for a "person.circle" icon and "Profile" text. Tapping each tab item instantly displays the corresponding view, and each view can have its own independent navigation stack.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.