Reputation: 79
The Navigation Bar title is missing when I put the view within a TabView. Anyone know what's the problem?
struct ContentView: View {
var body: some View {
NavigationView {
TabView {
Text("Tab 1")
.tabItem {
Text("Tab 1")
}
.navigationBarTitle("Tab 1")
.navigationBarHidden(false)
Text("Tab 2")
.tabItem {
Text("Tab 2")
}
.navigationBarTitle("Tab 2")
.navigationBarHidden(false)
}
}
}
}
This is what I wish to achieve:
Upvotes: 1
Views: 1195
Reputation: 257711
A possible approach is to join navigation view title with tab view selection dynamically, like
struct ContentView: View {
let tabs = ["Tab 1", "Tab 2"] // can be in model
@State private var selection: String
init() {
_selection = State(initialValue: tabs[0]) // initial tab
}
var body: some View {
NavigationView {
TabView(selection: $selection) { // << here !!
Text("Tab 1")
.tabItem {
Text("Tab 1")
}.tag(tabs[0])
Text("Tab 2")
.tabItem {
Text("Tab 2")
}.tag(tabs[1])
}
.navigationBarTitle(selection) // << here !!
}
}
}
TabBar
is designed to be a root view, so to achieve your needs the following approach can be used instead
struct ContentView: View {
var body: some View {
TabView {
NavigationView {
Text("Tab 1")
.navigationBarTitle("Tab 1")
.navigationBarHidden(false)
}
.tabItem {
Text("Tab 1")
}
NavigationView {
Text("Tab 2")
.navigationBarTitle("Tab 2")
.navigationBarHidden(false)
}
.tabItem {
Text("Tab 2")
}
.navigationBarTitle("Tab 2")
.navigationBarHidden(false)
}
}
}
Upvotes: 4