Search code examples
buttonswiftuibacknavigationviewswiftui-navigationlink

How to bind an action to the navigationview back button?


I would like to bind an action to the Back button in the navigationview toolbar, is it possible?

enter image description here

var body: some View {
     List {
          ForEach(mainViewModel.items) { item in
              NavigationLink(destination: EditTaskView(item: item)) {
                  HStack {
                      ListRowView(item: item)
                  }
              }
         }
     }
}

Solution

  • You can't bind directly to the back button, but you can have the navigation link itself be activated based on state, and then listen to the change of the state value like so. Do note that this requires that you manage the setting of state to true (no auto tap like with the default initializer)

    struct ContentView: View {
      @State private var showingNavView = false
      var body: some View {
        NavigationView {
          List {
            NavigationLink("Sub View", isActive: $showingNavView) {
              SubView()
            }.onTapGesture {
              showingNavView = true
            }.onChange(of: showingNavView) { newValue in
              print(newValue) // Will change to false when back is pressed
            }
          }
        }
      }
    }
    struct SubView: View {
      var body: some View {
        ZStack {
          Color.green
          Text("Cool Beans")
        }
      }
    }