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

2024-05-16

由于应用程序特定的原因,我必须将 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")
        }
    }
}

这是可能的解决方案。使用 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)
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SwiftUI - 在 NavigationView 中嵌套 TabView 时不显示导航栏标题 的相关文章

随机推荐