[英]SwiftUI: How can I get the selected row in a List before pushing another view
Another SwiftUI struggle!另一个 SwiftUI 斗争!
I have a view that contains a list.我有一个包含列表的视图。 When user taps on a row, I want to first save the selected item in my VM then push another view.当用户点击一行时,我想先将所选项目保存在我的 VM 中,然后再推送另一个视图。 The only way I can think of to solve that issue is to first save the selected row and have another button to push the next view.我能想到的解决该问题的唯一方法是首先保存所选行并使用另一个按钮来推送下一个视图。 It seems impossible to do this with only one tap.只需轻轻一按似乎不可能做到这一点。
Anyone have a clue?有人有线索吗?
Here's the code by the way:顺便说一下,这是代码:
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
}
}
}
}
}
Thank you!谢谢!
Alright, I found a not too shady solution.好吧,我找到了一个不太阴暗的解决方案。 I used this article https://ryanashcraft.me/swiftui-programmatic-navigation shout out to him!我用这篇文章https://ryanashcraft.me/swiftui-programmatic-navigation向他大喊大叫! Instead of using a NavigationLink
button, I use a regular button, save the selected item when the user tap then use NavigationDestinationLink
to push the new view as is self.link.presented?.value = true
.我没有使用NavigationLink
按钮,而是使用常规按钮,在用户点击时保存所选项目,然后使用NavigationDestinationLink
按self.link.presented?.value = true
推送新视图。
Works like a charm as of beta 3!从 Beta 3 开始,它就像一个魅力! I'll update my post if something change in the next betas.如果下一个测试版有什么变化,我会更新我的帖子。
Here's how it could look like:这是它的样子:
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)
}
}
}
}
}
}
You can add simple TapGesture您可以添加简单的 TapGesture
NavigationLink(destination: ContentView() ) {
Text("Row")
.gesture(TapGesture()
.onEnded({ _ in
//your action here
}))
}
这也可以通过在任何 View 继承者中使用 Publisher 和OnReceive
挂钩来完成。
Swift 5.1斯威夫特 5.1
In case you would like to apply it to a static List.如果您想将其应用于静态列表。 You may try this.你可以试试这个。
NavigationView{
List{
NavigationLink("YourView1Description", destination: YourView1())
NavigationLink("YourView2Description", destination: YourView2())
NavigationLink("YourView3Description", destination: YourView3())
NavigationLink("YourView4Description", destination: YourView4())
}
.navigationBarTitle(Text("Details"))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.