NEW: Learn SwiftUI with my free YouTube video series! >>

< How to add bar items to a navigation view   How to group views together >

How to embed views in a tab bar using TabView

SwiftUI’s TabView provides an equivalent to UITabBarController, allowing us to let the user switch between several active views using a bar at the bottom of the screen.

In its basic form, you should provide each item with an image and title, along with a tag so that SwiftUI knows which view is which. For example, this creates two views with different images, titles, and tags:

struct ContentView: View {    
    var body: some View {
        TabView {
            Text("First View")
                .tabItem {
                    VStack {
                        Image(systemName: "1.circle")
                        Text("First")
                    }
                }.tag(0)
            Text("Second View")
                .tabItem {
                    VStack {
                        Image(systemName: "2.circle")
                        Text("Second")
                    }
                }.tag(1)
        }
    }
} 

Even though we’ve used a VStack for the image and title, SwiftUI is smart enough to render them horizontally as appropriate – on iPhone in landscape, for example.

If you need it, those tags can be used to programmatically control the active tab. First, add some state that can track the active tab:

@State var selectedView = 1

Now pass that in to the TabView, like this:

TabView(selection: $selectedView) {

SPONSOR Meet the new Instabug – more than just bug reporting! We help you build better apps and minimize your debugging time. With each bug report, we automatically capture details like network requests, repro steps, and session details. Get real-time crash reports with stack trace details and session data to help you catch and fix issues easily. And with our customizable in-app surveys, you’ll gather insightful user feedback and much more. Instabug is the fastest and easiest way to release with confidence. Start your free trial now! Start your free trial now!

< How to add bar items to a navigation view   How to group views together >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>