barndog
barndog

Reputation: 7173

Shared toolbar items in SwiftUI NavigationStack

I have a navigation stack that's about three views deep. I want every single destination in this stack navigation to all have exactly the same toolbar items, a "Skip" button at the top right corner. However I can't for the life of me find a way to apply that button once at the top level and have it propagate down to the children. I understand that in SwiftUI, you add modifiers like .navigationTitle to the child views and they search up the view hierarchy but is there really no way to do the opposite?

What I want would ideally look like

NavigationStack {
    RootView()
}
    .toolbar {
        ToolbarItem(placement: .topBarTrailing) {
            Button(action: {}) { Text("Skip") }
        }
    }

But with how SwiftUI works I have to apply that on every single child view. Really? There's not a better way?

Upvotes: 4

Views: 732

Answers (1)

malhal
malhal

Reputation: 30746

Normally you would just make a View and use it in each place but in this case I think you need a ViewModifier like this:

struct MyToolBar: ViewModifier {
    func body(content: Content) -> some View {
        content
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                Button(action: {}) {     Text("Skip") }
            }
        }
     }

} 

Use in multiple places like:

NavigationStack {
    RootView()
    .modifier(MyToolBar())
}

Upvotes: -2

Related Questions