SwiftUI:在推送另一个视图之前,如何获取列表中的选定行

Ben*_*net 3 ios swift swiftui

另一个SwiftUI斗争!

我有一个包含列表的视图。当用户点击一行时,我想先将所选项目保存在我的VM中,然后再推送另一个视图。我能想到的解决该问题的唯一方法是,首先保存选定的行,然后使用另一个按钮来推送下一个视图。似乎仅需轻按一下即可完成此操作。

有人知道吗?

这是代码:

struct AnotherView : View {
    @State var viewModel = AnotherViewModel()

    var body: some View {
        NavigationView {
            VStack {
                    List(viewModel.items.identified(by: \.id)) { item in
                        NavigationLink(destination: DestinationView()) {
                            Text(item)
                        }
                        // Before the new view is open, I want to save the selected item in my VM, which will write to a global store.
                        self.viewModel.selectedItem = item
                    }
                }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Iva*_*kov 6

您可以添加简单的 TapGesture

                NavigationLink(destination: ContentView() ) {
                    Text("Row")
                        .gesture(TapGesture()
                            .onEnded({ _ in
                                //your action here
                    }))
                }
Run Code Online (Sandbox Code Playgroud)

  • 您可以只使用 `.onTapGesture { /* actions here */ }` 而不是 `.gesture(TapGesture()).onEnded({ ... })` (8认同)
  • 使用这种方法,不是只有在点击文本本身而不是整行时才执行“操作”吗?也就是说,如果点击位于文本范围之外,我相信会发生导航,但“操作”不会执行。 (7认同)

Ben*_*net 5

好吧,我找到了一个不太阴暗的解决方案。我用这篇文章https://ryanashcraft.me/swiftui-programmatic-navigation向他大喊大叫!NavigationLink我使用常规按钮,而不是使用按钮,而是在用户点击时保存所选项目,然后使用NavigationDestinationLink来按原样推送新视图self.link.presented?.value = true

像beta 3一样具有魅力!如果下一个测试版有所更改,我将更新我的帖子。

它看起来像这样:

struct AnotherView : View {
    private let link: NavigationDestinationLink<AnotherView2>
    @State var viewModel = AnotherViewModel()

    init() {
        self.link = NavigationDestinationLink(
            AnotherView2(),
            isDetail: true
        )
    }

    var body: some View {
        NavigationView {
            VStack {
                List(viewModel.items.identified(by: \.id)) { item in
                    Button(action: {
                        // Save the object into a global store to be used later on
                        self.viewModel.selectedItem = item
                        // Present new view
                        self.link.presented?.value = true
                    }) {
                        Text(value: item)
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您现在可以更新此内容,因为 NavigationDestinationLink 已在第一个 SwiftUI 版本中被弃用,那将非常有帮助。 (7认同)