SwiftUI iOS 13.3 Missing Navigation Bar title when nested inside TabView

1.1k Views Asked by At

The Navigation Bar title is missing when I put the view within a TabView. Anyone know what's the problem?

struct ContentView: View {
    var body: some View {
        NavigationView {
            TabView {
                Text("Tab 1")
                    .tabItem {
                        Text("Tab 1")
                    }
                    .navigationBarTitle("Tab 1")
                    .navigationBarHidden(false)

                Text("Tab 2")
                    .tabItem {
                        Text("Tab 2")
                    }
                    .navigationBarTitle("Tab 2")
                    .navigationBarHidden(false)
            }
        }
    }
}

This is what I'm getting:

This is what I wish to achieve:

1

There are 1 best solutions below

2
On

Update: Xcode 13.4 / iOS 15.5

A possible approach is to join navigation view title with tab view selection dynamically, like

demo1demo2

struct ContentView: View {
    let tabs = ["Tab 1", "Tab 2"]   // can be in model

    @State private var selection: String

    init() {
        _selection = State(initialValue: tabs[0]) // initial tab
    }

    var body: some View {
        NavigationView {
            TabView(selection: $selection) {   // << here !!
                Text("Tab 1")
                    .tabItem {
                        Text("Tab 1")
                    }.tag(tabs[0])

                Text("Tab 2")
                    .tabItem {
                        Text("Tab 2")
                    }.tag(tabs[1])
            }
            .navigationBarTitle(selection)    // << here !!
        }
    }
}

Original

TabBar is designed to be a root view, so to achieve your needs the following approach can be used instead

struct ContentView: View {
    var body: some View {
        TabView {
            NavigationView {
                Text("Tab 1")
                    .navigationBarTitle("Tab 1")
                    .navigationBarHidden(false)
            }
            .tabItem {
                Text("Tab 1")
            }

            NavigationView {
                Text("Tab 2")
                    .navigationBarTitle("Tab 2")
                    .navigationBarHidden(false)
            }
            .tabItem {
                Text("Tab 2")
            }
            .navigationBarTitle("Tab 2")
            .navigationBarHidden(false)
        }
    }
}