How do I use Swift UI to create a tab bar?
Asked on 2024-07-30
1 search
To create a tab bar using SwiftUI, you can use the new syntax introduced in iOS 18. Here's a step-by-step guide based on the information from the WWDC sessions:
-
Declare a Tab Struct: You need to declare a tab struct with a title, image, and its content view. Optionally, you can include a selection value to enable programmatic selection.
-
Ensure Type Safety: The new syntax ensures that all tabs have the same selection type and that the type matches the tab view itself.
-
Customization: You can enable user customization on a tab view by attaching a
TabViewCustomizationto the tab view. This allows various customization features like reordering and removing tabs.
Here is an example of how you might set up a basic tab bar in SwiftUI:
import SwiftUI
struct ContentView: View {
@State private var selectedTab = 0
var body: some View {
TabView(selection: $selectedTab) {
Text("First Tab")
.tabItem {
Image(systemName: "1.circle")
Text("First")
}
.tag(0)
Text("Second Tab")
.tabItem {
Image(systemName: "2.circle")
Text("Second")
}
.tag(1)
}
.tabViewStyle(DefaultTabViewStyle())
}
}
Additional Features
-
Customization: To enable user customization, you can use the
TabViewCustomizationmodifier. This allows users to reorder tabs and hide infrequently used options. -
Sidebar Adaptable: You can make your tab view more flexible by applying the new sidebar adaptable tab view style. This allows switching between a tab bar and a sidebar view.
For more detailed information, you can refer to the session Elevate your tab and sidebar experience in iPadOS at the timestamp 04:28.
Relevant Sessions
These sessions provide comprehensive insights into the new tab bar features and how to implement them using SwiftUI.

Elevate your tab and sidebar experience in iPadOS
iPadOS 18 introduces a new navigation system that gives people the flexibility to choose between using a tab bar or sidebar. The newly redesigned tab bar provides more space for content and other functionality. Learn how to use SwiftUI and UIKit to enable customization features – like adding, removing and reordering tabs – to enable a more personal touch in your app.

What’s new in SwiftUI
Learn how you can use SwiftUI to build great apps for any Apple platform. Explore a fresh new look and feel for tabs and documents on iPadOS. Improve your window management with new windowing APIs, and gain more control over immersive spaces and volumes in your visionOS apps. We’ll also take you through other exciting refinements that help you make expressive charts, customize and layout text, and so much more.

Migrate your TVML app to SwiftUI
SwiftUI helps you build great apps on all Apple platforms and is the preferred toolkit for bringing your content into the living room with tvOS 18. Learn how to use SwiftUI to create familiar layouts and controls from TVMLKit, and get tips and best practices.
