如何将动作绑定到导航视图后退按钮?

How to bind an action to the navigationview back button?

您好,我想将一个动作绑定到导航视图工具栏中的后退按钮,可以吗? picture about the situation

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

你不能直接绑定后退按钮,但是你可以让导航link本身根据状态被激活,然后像这样监听状态值的变化。请注意,这需要您将状态设置管理为 ​​true(没有像默认初始化程序那样的自动点击)

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")
    }
  }
}