Dynamically set SwiftUI NavigationBarItems?

1.3k views Asked by At

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)
        }
1

There are 1 answers

1
Asperi On BEST ANSWER

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"){}
                }
            })
        }
    }
}