问题
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