dankito
dankito

Reputation: 1108

SwiftUI - Navigation bar title not displayed when nesting TabView in NavigationView

Due to application specific reasons I have to nest a TabView in a NavigationView. But then the navigation bar title of the tab items doesn't get displayed, just an empty navigation bar.

Any solutions to this?

struct ContentView: View {
    var body: some View {
        NavigationView {
            TabView {
                Text("Tab 1")
                .navigationBarTitle("Tab 1") // is ignored, only an empty string is displayed
                .tabItem {
                    Text("Tab 1")
                }
                
                Text("Tab 2")
                .navigationBarTitle("Tab 2") // is ignored, only an empty string is displayed
                .tabItem {
                    Text("Tab 2")
                }
            }
            // this would display a navigation bar title, but then the title is the same for all tab items
            //.navigationBarTitle("TabView title")
        }
    }
}

Upvotes: 2

Views: 1041

Answers (2)

bugmaker
bugmaker

Reputation: 11

if let NavigationView outside TabView ,when you push a new View and change current App,when you return you app ,if will always pop to TabView

Upvotes: 1

Asperi
Asperi

Reputation: 258581

Here is possible solution. Tested with Xcode 11.4 / iOS 13.4

struct ContentView: View {
    @State private var title = ""
    var body: some View {
        NavigationView {
            TabView {
                Text("Tab 1")
                .onAppear { self.title = "Tab 1" }
                .tabItem {
                    Text("Tab 1")
                }

                Text("Tab 2")
                .onAppear { self.title = "Tab 2" }
                .tabItem {
                    Text("Tab 2")
                }
            }
            .navigationBarTitle(title)
        }
    }
}

Upvotes: 2

Related Questions