3

I have four Views inside a TabView and each of them contains NavigationView with title. However, when the view first shows up, the navigation view does not show as designed.

Even though I have the navigation bar item, the view would always be a blank child view. It is only when I click to another page and then coming back to the navigation view that the view would show normally. What could be the problems?

Attached is the screenshot of the preview page. Thanks in advance.

struct MainContentView: View {
    @State private var navSelection = 0
    
    var body: some View {
        
        VStack(alignment: .center){
          
            TabView(selection:$navSelection){
                NavigationView{
                    HomeView()
                        .navigationBarItems(leading: Text("Title").font(.system(size:24,weight: .heavy)), trailing: Image(systemName: "bell.fill"))
                        .navigationViewStyle(StackNavigationViewStyle())
                       
                }.tag(0)
                
                NavigationView{
                    ExploreView()
                       
                }.tag(1)
        
                Text("Post").tag(2)
                Text("Market").tag(3)
                Text("Account").tag(4)
            }.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
                .disabled(true)
            
            MainTabBarView(navSelection: self.$navSelection)
            }
    }
}

enter image description here

The preview sample

jnpdx
  • 45,847
  • 6
  • 64
  • 94
cc nn
  • 115
  • 1
  • 1
  • 7
  • Interesting bug... it looks like PageTabViewStyle tab view uses internally navigation stack as well which conflicts with your child navigation view stack. – Asperi Jan 30 '22 at 06:58
  • Wow... then does it mean I do not have to specify the navigation view at this stage and use the navigation link directly inside the home view? – cc nn Jan 30 '22 at 07:33
  • @ccnn or just get rid of the tab view and make your own custom one. Might be more customizable – aheze Jan 30 '22 at 07:36
  • had to just give up the tabview, thx! – cc nn Feb 10 '22 at 04:27

1 Answers1

2

Just a small mistake, apply the style to the navigation view as follows:

NavigationView{ 
}
.navigationViewStyle(.stack)
         

What went wrong is some how SwiftUI found a detail view somewhere in the hierarchy and pushed it because normally inside NavigationView there are two views defined but you only defined one. I think .tabViewStyle is what caused it.

Also to set the nav item title we use .navigationTitle("Home")

malhal
  • 26,330
  • 7
  • 115
  • 133