In SwiftUI how do I put the tabs in a TabbedView at the top of the view?

Viewed 6226

I have a view with tabs on the bottom, one of the views has subviews, to separate the logic visually, I put the tabs of the subview at the top of the view with the following code and it works perfectly:

self.tabbar.frame = CGRect( x: 0,
                            y: view.safeAreaInsets.top,
                            width: self.view.frame.size.width,
                            height: 50)

How do I do this in SwiftUI?

1 Answers

In order to do this you could create your tabs view as a container of the individual tabs something like this...

struct TabbedView: View {

    @State private var selectedTab: Int = 0

    var body: some View {
        VStack {
            Picker("", selection: $selectedTab) {
                Text("First").tag(0)
                Text("Second").tag(1)
                Text("Third").tag(2)
            }
            .pickerStyle(SegmentedPickerStyle())

            switch(selectedTab) {
                case 0: FirstTabView()
                case 1: SecondTabView()
                case 2: ThirdTabView()
            }
        }
    }
}

Doing this, you are conditionally populating the "Tab page" based on the value of the segmented control.

By using @State and $selectedTab the segmented control will update the selectedTab value and then re-render the view which will replace the page based on the new value of selectedTab.

Edit

Switches now work in SwiftUI beta.

Related