forrest
forrest

Reputation: 11012

How do I navigate to a new View from a navigationBarItem without using Sheets?

I have an "add" button in the navigationBar of my app and I would like to display another view that fills the View instead of appearing modally like the view does by default when using Sheets.

Here is the code:

.navigationBarItems(leading: EditButton(), trailing: Button(action: {
         self.showingAddScreen.toggle()
     }) {
         Image(systemName: "plus")
     })
     .sheet(isPresented: $showingAddScreen) {
         NavigationView {
             AddTaskView().environment(\.managedObjectContext, self.moc)
         }
 }

NavigationLink pushes another view onto the stack. Is it possible to use NavigationLink with navigationBarItems or is there a better way to display the desired view full screen?

Upvotes: 0

Views: 66

Answers (2)

Pedro Cavaleiro
Pedro Cavaleiro

Reputation: 932

There's no problem in using NavigationLink in bar button items.

To make the code cleaner instead of creating the code inline like this

.navigationBarItems(trailing: NavigationLink(destination: SecondView()) { Image(systemName: "plus") })

I would create a computed property

var addButton: some View {
    NavigationLink(destination: SecondView()) { Image(systemName: "plus") })
}

// [...]
.navigationBarItems(trailing: addButton)

Make sure that you have a NavigationView on the first view only

If you want something more complex take a look into this post How To Navigate Between Views In SwiftUI By Using An @ObservableObject

It's what I'm using in my current project

Upvotes: 2

Timothy Stokarski
Timothy Stokarski

Reputation: 272

Have you tried something like this?

.navigationBarItems(leading: NavigationLink(destination: YourAnotherView(), label: {
                Text("Your Label or Icon")
            }), trailing: NavigationLink(destination: YourAnotherView(), label: {
                Text("Your label or Icon")
            }))

Upvotes: 1

Related Questions