简体   繁体   English

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

[英]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.由于特定于应用程序的原因,我必须将 TabView 嵌套在 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")
        }
    }
}

Here is possible solution.这是可能的解决方案。 Tested with Xcode 11.4 / iOS 13.4使用 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)
        }
    }
}

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如果让 NavigationView 在 TabView 之外,当你推送一个新的 View 并改变当前的应用程序时,当你返回你的应用程序时,如果总是弹出到 TabView

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM