2

How can you dynamically change SwiftUI Navigation Bar Items?

I have a TabView within a NavigationView, and I would like the Navigation Bar Items to change depending on tab that is selected. However, I am having a hard time determining how to change this with .onAppear(), assuming that is even what you are suppose to do.

My code is currently laid out as follows:

var body: some View {
        NavigationView {
            TabView {
                contentWithNavigationButtons()
                    .tabItem {
                        Image(systemName: "house")
                        Text("Buttons")
                    }
                
                contentWithoutNavigationButtons()
                    .tabItem {
                        Image(systemName: "person")
                        Text("No Buttons")
                    }
                    .onAppear {
                        //Navigation Bar Items should be removed
                    }
                
            }
            .navigationBarItems(trailing: someButton)
        }
Brandogs
  • 145
  • 13

1 Answers1

4

Here is a demo of possible solution - add tracking selection for tabs and make button depending of tab selection. Tested with Xcode 12 / iOS 14

struct DemoView: View {
    @State private var selection = 0    // << here !!
    var body: some View {
        NavigationView {
            TabView(selection: $selection) {
                contentWithNavigationButtons()
                    .tabItem {
                        Image(systemName: "house")
                        Text("Buttons")
                    }.tag(0)                // << here !!
                
                contentWithoutNavigationButtons()
                    .tabItem {
                        Image(systemName: "person")
                        Text("No Buttons")
                    }.tag(1)
                
            }
            .navigationBarItems(trailing: Group {
                if selection == 0 {     // << here !!
                    Button("Some"){}
                }
            })
        }
    }
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • What would be the recommended way to dispatch a click event on nav bar item from parent view to subview? The solution I can think of: If I've 4 tabs each with 2 nav bar items, I'd have to track 8 bool bindings in order to communicate the events from tabview to its destination - which feels a bit ugly to me :/ – Siddharth Kamaria Jul 05 '21 at 14:16