Search code examples
swiftuitabview

SwiftUI - Putting a bar above the TabView?


enter image description here

I want to put a bar above the TabView, as shown. Currently I'm achieving this by coding it at the bottom on the main views. I'd like to unify the code and put it into the TabView as a one off.

var body: some View {
    VStack {
        TabView(selection: $tabs.selectedTab) {
            LocationView()
                .tabItem {
                    Label("Location", systemImage: "globe.europe.africa")
                }
                .tag(TabChoice.location)
            CalculateView()
                .tabItem {
                    Label("Calculate", systemImage: "apps.ipad")
                }
                .tag(TabChoice.calculate)
            InstallView()
                .tabItem {
                    Label("Install", systemImage: "window.ceiling.closed")
                }
                .tag(TabChoice.install)
            ResultsView()
                .tabItem {
                    Label("Results", systemImage: "sun.max.fill")
                }
                .tag(TabChoice.results)
            AboutView()
                .tabItem {
                    Label("About", systemImage: "gear")
                }
                .tag(TabChoice.about)
        } // TabView
    }
}    

My efforts to date display the bar at the top of the screen whilst the Tab Bar remains at the bottom, where it should be.

Can this be done?


Solution

  • You could achieve this using a ZStack and adding a line on top of the TabBar. You can use a fixed height for this as in my example, however you might want to calculate the actual height of the TabBar and offset your line with that value instead. Take a look here: https://stackoverflow.com/a/60136275/12764203

    struct ContentView: View {
        var body: some View {
            ZStack {
                TabView {
                    Tab1()
                        .tabItem {
                            Label("Tab1", systemImage: "star")
                        }
                    Tab2()
                        .tabItem {
                            Label("Tab2", systemImage: "star")
                        }
                }
    
                VStack {
                    Spacer()
                    Rectangle()
                        .frame(maxWidth: .infinity, maxHeight: 1)
                        .foregroundColor(.red)
                        .padding(.bottom, 60)
                }
            }
        }
    }
    

    TabBar line example