Search code examples
swiftuiswiftui-navigationlinkswiftui-navigationviewswiftui-tabview

Swiftui - Handling Tab navigation inside a root navigation properly


The structure of my swiftUI app navigation is as below

View : A
{

Navigation View {
     // List View on click 
     // Takes me to a Tab View
     NavigationLink(destination : Tab View)

}

}
View : Tab View
{
       ViewX 
            .tag(0)
            .tabItem {
                Image(systemName: "video.bubble.left.fill")
                Text("View X")
                    .font(Font.custom("Roboto-Black", size: 30))
            }
       ViewY 
            .tag(0)
            .tabItem {
                Image(systemName: "video.bubble.left.fill")
                Text("View Y")
                    .font(Font.custom("Roboto-Black", size: 30))
            }

}

With this structure I'm not able to control the navigation title of the view correctly. If I wrap each tab item in a navigation view, I end up with multiple navigation title bars as expected. Any particular approach (like hiding the root navigation bar) to have one navigation bar with appropriate title updates in nested views ?


Solution

  • you won't be able to update the navigation Title automatically you will need to do something like this:

    import SwiftUI
    
    enum Tabs: String {
        case view1
        case view2
    }
    
    struct tab: View {
    
    @State var activeTab = Tabs.view1
    
    var body: some View {
        TabView(selection: $activeTab)
        {
            Text("View1")
                .tag(Tabs.view1)
                    .tabItem {
                        Image(systemName: "video.bubble.left.fill")
                        Text("View X")
                            .font(Font.custom("Roboto-Black", size: 30))
                    }
                   
            Text("View2")
                .tag(Tabs.view2)
                    .tabItem {
                        Image(systemName: "video.bubble.left.fill")
                        Text("View Y")
                            .font(Font.custom("Roboto-Black", size: 30))
                    }
                 
    
        }
        .navigationTitle("Active View: \(activeTab.rawValue)")
    }
    }
    

    enter image description here