PageTabViewStyle breaks NavigationView

Viewed 651

I am working on a SwiftUI view. When using the NavigationView inside the TabView the app works as expected.

struct ContentView: View {
    
    var body: some View {
        TabView {
            NavigationView {
                Text("A")
                    .navigationBarTitle("Nav A")
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            NavigationView {
                Text("B")
                    .navigationBarTitle("Nav B")
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
        //.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never)) // this line breaks the view
    }
}

As soon as I uncomment .tabViewStyle(...) the view does not work as expected. Any ideas why? The text is not visible anymore. The navigation does not seem to be correct either.

Works fine without PageTabViewStyle

PageTabViewStyle breaks view

2 Answers

Try moving the NavigationView outside the TabView:

struct ContentView: View {
    @State var selection = 1

    var body: some View {
        NavigationView {
            TabView(selection: $selection) {
                Text("A").tag(1)
                Text("B").tag(2)
            }
            .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
            .navigationTitle(selection == 1 ? "A" : "B")
        }
    }
}

It seems like the NavigationView defaults to presenting as a primary/detail display.

You can force it to work like a normal navigation stack with the modifier .navigationViewStyle(StackNavigationViewStyle())

Here it is in your code:

struct ContentView: View {

var body: some View {
    TabView {
        NavigationView {
            Text("A")
                .navigationBarTitle("Nav A")
        }
        .navigationViewStyle(StackNavigationViewStyle())
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        NavigationView {
            Text("B")
                .navigationBarTitle("Nav B")
        }
        .navigationViewStyle(StackNavigationViewStyle())
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
    .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never)) 
}

}

Related