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

1

9

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?

Phobos answered 7/6, 2019 at 15:47 Comment(0)
O
16

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. πŸ‘πŸ»

Overspill answered 12/6, 2019 at 13:28 Comment(5)
Unfortunately, at least in b1, we cannot use switch in ViewBuilders. Closure containing control flow statement cannot be used with function builder 'ViewBuilder' – Golda
@SteveRiggins thanks, that's a pain. Updated my answer for now though. Thanks – Overspill
Control flow statements inside a @ViewBuilder block are not "conventional" - they get translated by the compiler via @_functionBuilder structs, that enable the powerful SwiftUI DSL. switch won't work, as it is not part of the function builders proposal. – Contraposition
@Fogmeister, where did you get SegmentedControl from? – Gertiegertrud
@NicoCobelo Perhaps from UISegmentedControl. "A horizontal control that consists of multiple segments, each segment functioning as a discrete button." – Macula

© 2022 - 2024 β€” McMap. All rights reserved.