8

For the reason outlined in the answer outlined in this question SwiftUI TabView brightness views vertical location the menu structure for my app is NavigationView -> TabView -> sub view with varying navigation titles.

The problem is that .navigationTitle gives one navigation title for the whole TabView rather than one for each sub view. How do I have multiple navigation titles with TabView, one for each sub-view?

struct ContentView: View {
    var body: some View {
        NavigationView {
            TabView {
                Text("Hello")
                    .navigationTitle("Title One")
                    .tabItem {
                        Image(systemName: "square.stack")
                }
                Text("Hello Again")
                    .navigationTitle("Title Two")
                    .tabItem {
                        Image(systemName: "checkmark.square")
                }
            }
        }
    }
}
John Sorensen
  • 710
  • 6
  • 29

1 Answers1

8

We can define title depending on tab selection. Below is a simple demo of approach. Tested with Xcode 13 / iOS 15

struct ContentView: View {
    @State var selection = 1

    var body: some View {
        NavigationView {
            TabView(selection: $selection) {
                Text("Hello")
                    .tabItem {
                        Image(systemName: "square.stack")
                }.tag(1)
                Text("Hello Again")
                    .tabItem {
                        Image(systemName: "checkmark.square")
                }.tag(2)
            }
            .navigationTitle(selection == 1 ? "First" : "Second") // << here !!
        }
    }
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 1
    This works but when you try adding a navigation bar button it does not show up. Apparently a `TabView` should not go inside a `NavigationView` but the other way around. See https://stackoverflow.com/a/60933674. – John Mar 21 '22 at 19:48
  • Putting the NavigationStack inside the TabView means my NavigationDestingation(isPresented:) view docent cover the TabBar and that make for strange functionality. But I can't figure out how to set the titles properly the other way around – Kurt L. Nov 24 '22 at 23:04