Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 416
J. Edgell Avatar asked Jun 07 '19 15:06

J. Edgell


People also ask

How do I add a tab bar in SwiftUI?

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.

Which control is used to displaying the tabbed page view?

The TabView control is a way to display a set of tabs and their respective content.

How do I hide the tab bar in SwiftUI?

If we want to hide the TabBar , we just write TabView into NavigationView , making the NavigationView the super-view and the TabView the child-view, which is just opposite to the above View Hierarchy .


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. 👍🏻

like image 184
Fogmeister Avatar answered Sep 26 '22 14:09

Fogmeister