iosswiftswiftuiswiftui-tabview

How to move SwiftUI Bottom Tab to the top?


The following SwiftUI code will generate Bottom Tab

public struct TeamBContentView : View {
    public init() {}
    public var body: some View {
        VStack {
            TabView {
                Text("This is home screen")
                    .tabItem {
                        Text("Home")
                        Image(systemName: "house.fill")
                    }
                Text("This is about us screen")
                    .tabItem {
                        Text("About Us")
                        Image(systemName: "person.fill")
                    }
                Text("This is contct us screen")
                    .tabItem {
                        Text("Contact Us")
                        Image(systemName: "phone.fill")
                    }
            }
        }
    }
}

As below

enter image description here

If I want to have it at the Top, is there a way easily transfer it to the Tab to the top of the screen instead?


Solution

  • public struct TeamBContentView : View {
    @State private var selectedTab = 0
    public init() {}
    
    public var body: some View {
        VStack {
            // Use picker view and set picker style as segmented
            Picker("Tabs", selection: $selectedTab) {
                Text("Home").tag(0)
                Text("About Us").tag(1)
                Text("Contact Us").tag(2)
            }
            .pickerStyle(.segmented)
            .padding()
            
            Spacer()
            
            // Then display the view based on the tab selected
            switch selectedTab {
            case 0:
                Text("This is home screen")
            case 1:
                Text("This is about us screen")
            case 2:
                Text("This is contact[enter image description here][1] us screen")
            default:
                Text("This is home screen")
            }
            Spacer()
        }
        .navigationBarBackButtonHidden() // use this to hide the back button
    }
    }