Another SwiftUI struggle!
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. 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!
itemin yourDestinationViewinitializer? While it won't immediately updateanotherViewModel, it can in the initializer. Also, If you have a view model, please look into using@BindableObjectinstead of@State, and then either@ObjectBindingor@EnvironmentObject. The sooner the better, it'll give you a better route to work through these things. :-) Otherwise,you'll find yourself with... spaghetti state!@BindableObjectbtw) will write into this global store. At the end of the flow, I will use that store to gather all data. That way, all views are independent and I don't need to pass an object over and over.@EnvironmentObjectis.Listinfer that the only thing we need to do when we select an item is open a view with more detail about that item.SwiftUIand/orCombineis "by reference" not "by value", and (2) aListbased on a dynamic array requires astructthat conforms toIdentifiable. You don't need to "pass the object and then update the model", you just need to "pass a pointer to the object id already in the model". The memory footprint is the same. (Part of what I call "the paradigm change" - wish I could copyright that - fromUIKit.)