8

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?

bruno
  • 32,421
  • 7
  • 25
  • 37
J. Edgell
  • 1,555
  • 3
  • 16
  • 24

1 Answers1

14

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.

sublimeike
  • 182
  • 1
  • 1
  • 10
Fogmeister
  • 76,236
  • 42
  • 207
  • 306
  • 2
    Unfortunately, at least in b1, we cannot use switch in ViewBuilders. `Closure containing control flow statement cannot be used with function builder 'ViewBuilder'` – Steve Riggins Jun 14 '19 at 03:32
  • @SteveRiggins thanks, that's a pain. Updated my answer for now though. Thanks – Fogmeister Jun 14 '19 at 09:40
  • 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](https://github.com/apple/swift-evolution/blob/9992cf3c11c2d5e0ea20bee98657d93902d5b174/proposals/XXXX-function-builders.md). – Matteo Pacini Jun 14 '19 at 09:47
  • 2
    @Fogmeister, where did you get SegmentedControl from? – Nico Cobelo Feb 11 '21 at 19:48
  • @NicoCobelo Perhaps from [UISegmentedControl](https://developer.apple.com/documentation/uikit/uisegmentedcontrol). _"A horizontal control that consists of multiple segments, each segment functioning as a discrete button."_ – kwiknik Feb 16 '23 at 21:35