Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI TabbedView only shows first tab's content

Tags:

ios

swift

swiftui

I'm trying to build a TabbedView with the following simple code:

TabbedView {
    Text("Hello world")
        .tabItemLabel(Text("Hello"))
    Text("Foo bar")
        .tabItemLabel(Text("Foo"))
}

When running, both tabs are visible and enabled but the second tab's ("Foo") content is blank.

like image 473
Natanel Avatar asked Jun 06 '19 22:06

Natanel


People also ask

What is TabView in SwiftUI?

A view that switches between multiple child views using interactive user interface elements.

What is tab view?

The View tab enables you to switch between Normal or Master Page, and Single Page or Two-Page Spread views. This tab also gives you control over showing boundaries, guides, rulers, and other layout tools, zooming the size of your view of the publication, and managing Publisher windows you have open.

How do I add a tab view in Swift?

Press Cmd+N to create a new SwiftUI View, calling it “MainView”. 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.

How do I change the tab bar color in SwiftUI?

To change a tab bar background color in SwiftUI, you apply toolbarBackground modifier to the child view of TabView . Make sure you apply toolbarBackground to a child view, not a TabView . toolbarBackground accepts two parameters. ShapeStyle : The style to display as the background of the bar.


2 Answers

Try adding tags:

    TabbedView {
        Text("Hello world")
            .tabItem { Text("Hello") }
            .tag(0)
        Text("Foo bar")
            .tabItem { Text("Foo") }
            .tag(1)
    }
like image 112
Bradley Hilton Avatar answered Sep 17 '22 21:09

Bradley Hilton


I was able to fix this by adding a selection state variable and passing that in for the selection:

struct ContentView : View {
    @State private var selection = 1

    var body: some View {
        TabbedView(selection: $selection) {
            Text("Tab 1!").tabItemLabel(
                Text("Tab 1")).tag(1)
            Text("Tab 2!").tabItemLabel(Text("Tab 2")).tag(2)
        }
    }
}

Now, tapping "Tab 2" will show "Tab 2!" on the screen, as opposed to a blank screen.

This was using Xcode 11.0 beta 2 (11M337n), macOS Catalina 10.15 Beta (19A487l).

like image 42
Mike Buss Avatar answered Sep 20 '22 21:09

Mike Buss