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

≯℡__Kan透↙ 提交于 2020-08-08 05:15:19

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/63115644/swiftui-navigation-bar-title-not-displayed-when-nesting-tabview-in-navigationv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!