swiftuiswiftui-navigationlinkswiftui-navigationview

Migrating to NavigationStack with .toolbar


Currently, I have a settings button inside the toolbar that when I tap on it it will open the SettingsView(). Here's my implementation below.

@State private var goToSettings = false

NavigationView {
   ZStack {
      NavigationLink(destination: SettingsView(), isActive: $goToSettings) {
      }
   }
   .toolbar {
      Button(role: .destructive, action: {
         goToSettings = true
      }) {
         Label("Settings", systemImage: "gearshape.fill").foregroundColor(colorForeground)
      }
   }
}

Now what confuses me right now is how to implementation this with NavigationStack? Where should I put NavigationLink because it seems to not work inside the .toolbar?

Thanks!


Solution

  • The solution was a little straightforward I found out.

    Instead of NavigationView, you use the new and shiny NavigationStack. And use .navigationDestination() instead of NavigationLink.

    @State private var goToSettings = false
    
    NavigationStack {
       ZStack {
          // Some more codes
       }
       .toolbar {
          Button(role: .destructive, action: {
             goToSettings = true
          }) {
             Label("Settings", systemImage: "gearshape.fill").foregroundColor(colorForeground)
          }
       }
       .navigationDestination(isPresented: $goToSettings) {
           SettingsView()
       }
    }