Swiftui导航视图 - 从一个孩子视图导航到另一个孩子

发布于 2025-01-17 14:17:56 字数 983 浏览 3 评论 0原文

我使用带有标签/选择初始值设定项的 NavigationView,它允许通过 UI 和以编程方式通过更改绑定的值 (model.currentItemId) 来控制所选的详细视图:

@EnvironmentObject var model: Model
var items: [Item]

var body: some View {
  NavigationView {
    List {
      ForEach(items) { item in
        NavigationLink(
          tag: item.id,
          selection: $model.currentItemId,
          destination: { ItemView(item: item) },
          label: { ItemPreview(item: item) },
        )
      }
    }
  }
}

它通常运行良好;现在,我需要通过单击按钮从一个详细信息视图 (ItemView) 导航到另一个详细信息视图:

struct ItemView(): View {
  @EnvironmentObject var model: Model
  var item: Item

  var body: some View {
    // ...
    Button("open") {
      model.currentItemId = 20 // it is in the list, but not on the screen
    }
    // ...
  }
}

它不是打开所需的详细信息视图,而是打开列表视图。

但是,如果我将列表滚动到表示所需详细视图的项目,它将跳入此详细视图,无需任何用户操作 - 只要该项目出现在屏幕上。

有没有办法克服它并在不显示项目的情况下打开详细视图?或者我是否必须以某种方式指示 NavigationView 将此项目滚动到视图中?

谢谢你!

I am using a NavigationView with tag/selection initializer that allows controlling the selected detail view both via UI and programmatically, by changing the value of the binding (model.currentItemId):

@EnvironmentObject var model: Model
var items: [Item]

var body: some View {
  NavigationView {
    List {
      ForEach(items) { item in
        NavigationLink(
          tag: item.id,
          selection: $model.currentItemId,
          destination: { ItemView(item: item) },
          label: { ItemPreview(item: item) },
        )
      }
    }
  }
}

It generally works well; now I need to navigate from one detail view (ItemView) to another on the button click:

struct ItemView(): View {
  @EnvironmentObject var model: Model
  var item: Item

  var body: some View {
    // ...
    Button("open") {
      model.currentItemId = 20 // it is in the list, but not on the screen
    }
    // ...
  }
}

and instead of opening the required detail view, it opens the list view.

But if I scroll the list to the item representing the required detail view it would jumps into this detail view without any user action - as soon as this item appears on the screen.

Is there a way to overcome it and open detail view without having the item visible? Or do I have to somehow instruct NavigationView to scroll this item into the view?

Thank you!

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文