SwiftUi Navigation Bar Button disappears after entering the third View (Controller)

Viewed 3437

I have a huge Problem with SwiftUi. The "Backbutton" in a really Simple NavigationView Hierarchy disappears on the third View. If I go one view further, the Backbutton is there again and I can go back.

I searched like 3 Hours but only found this SwiftUI: Back button disappears when clicked on NavigationLink

Obviously this doesn't solve my Problem.

Thanks for any Help!

7 Answers

For me the issue was a bit different - the back button disappeared on the third view only after interacting with the third view, e.g. clicking into the list view.

My workaround is to use the old .navigationBarItems instead of .toolbar, so:

 .navigationBarItems(trailing:
    Menu {
       Button(action: {
          //some action
       }) {
          //some label
       }
       Button(action: {
          //some action
       }) {
          //some label
       }                                        
    }
    label: {
       //some label
    }
 )

instead of:

.toolbar {
   ToolbarItem(placement: .navigationBarTrailing) {
      Menu {
         Button(action: {
            //some action
         }) {
            //some label
         }
         Button(action: {
            //some action
         }) {
            //some label
         }                        
      }
      label: {
         //some label
      }
   }
}

I found another workaround for who doesn't want to use a deprecated method.

Just add in your .toolbar this ToolBarItem:

.toolbar {

    // ... other toolbar items

    ToolbarItem(placement: .navigationBarLeading) {
        Text("")
    }
}

Another solution which seems to be working on Xcode 12.4:

ToolbarItem(placement: .navigationBarLeading) {
    HStack {}
}

In case you want to make your code cleaner

/// A ToolbarItem wrapper to work around the back button disappearance bug in SwiftUI 2.
struct NavbarBackButtonDisappearanceWorkaroundItem: ToolbarContent {
    var body: some ToolbarContent {
        ToolbarItem(placement: .navigationBarLeading) {
            Color.clear
        }
    }
}

Use as follows:

.toolbar {
   NavbarBackButtonDisappearanceWorkaroundItem()
   SomeOtherUsefulItem()        
}

I found the Problem!

The .toolbar modifier on the NavigationView hides the Backbutton in a Buggy way!

I have found the solution of this problem. If you are not using .toolbar nor .navigationBarItems you should simply add .navigationBarItems(trailing: EmptyView()) to you children. This will always keep your back button alive)

   var body: some View {
      ScrollView() {
        ...
      }
       .navigationBarItems(trailing: EmptyView())
     }

'''

you need to add to your NavigationView

.navigationViewStyle(StackNavigationViewStyle())
Related