如何将动作绑定到导航视图返回按钮?

发布于 2025-01-20 18:34:56 字数 505 浏览 4 评论 0原文

我想将动作绑定到导航视图工具栏中的后退按钮,是否有可能?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

本王不退位尔等都是臣 2025-01-27 18:34:56

您不能直接绑定到后退按钮,但您可以根据状态激活导航链接本身,然后像这样监听状态值的变化。请注意,这要求您将状态设置管理为 ​​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")
    }
  }
}

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")
    }
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文