SwiftUI-在NavigationView中嵌套TabView时不显示导航栏标题

时间:2020-07-27 12:45:46

标签: swiftui

由于特定于应用程序的原因,我必须将TabView嵌套在NavigationView中。但是,这样就不会显示选项卡项目的导航栏标题,而只是显示一个空的导航栏。

有什么解决办法吗?

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")
        }
    }
}

1 个答案:

答案 0 :(得分:2)

这是可能的解决方案。使用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)
        }
    }
}