SwiftUI 的另一场斗争!
我有一个包含列表的 View 。当用户点击一行时,我想先将所选项目保存在我的 VM 中,然后再推送另一个 View 。 我能想到的解决该问题的唯一方法是首先保存选定的行并使用另一个按钮来推送下一个 View 。似乎不可能只点击一下就可以做到这一点。
有人知道吗?
顺便说一句,这是代码:
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
}
}
}
}
}
谢谢!
最佳答案
好吧,我找到了一个不太阴暗的解决方案。
我用了这篇文章https://ryanashcraft.me/swiftui-programmatic-navigation对他大声喊叫!
我没有使用 NavigationLink
按钮,而是使用常规按钮,在用户点击时保存所选项目,然后使用 NavigationDestinationLink
按原样推送新 View 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)
}
}
}
}
}
}
关于ios - SwiftUI:如何在推送另一个 View 之前获取列表中的选定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57058209/