Home > front end >  NavigationLink not working inside a button
NavigationLink not working inside a button

Time:11-10

I have added a ToolBarItemGroup with a button that should navigate to another view.

But in this case the button with navigationLink does not work

It is because I am not able to add a navigationLink to .toolbar?

VStack {
    NavigationView {
         List {

         }.toolbar {
             ToolbarItemGroup(placement: .navigationBarTrailing) {
                 Button("MyButton") {
                      NavigationLink(Destination: ContentView()) {
                          ContentView()
                      }
                 }
             }
         }

Whenever I click the MyButton, it does not navigate to my ContentView. What I am doing wrong here? I want to use the button in the toolbar

CodePudding user response:

NavigationLink is actually a type of button, albeit one with different constructors and default styling (for example, when you use it inside a List).

In your example code, you're putting it inside another button's action closure, which should contain code to execute rather than SwiftUI views.

Your toolbar can be more simply expressed as:

.toolbar {
  NavigationLink("MyButton") {
    ContentView()
  }
}
  • Related