Currently i am using subview without using viewmodel and which is woking fine..UI is updating on value change. (find code below) but i want to create viewmodel for subview and update UI on value change..
Normal code without viewmodel
struct MainView: View {
@State private var selectedTag: String?
var body: some View {
VStack {
ForEach(products, id: \.description) { item in
SubView(productTag: item.productId, selectedTag: self.$selectedTag)
}
}
}
}
struct SubView: View {
var productTag: String?
@Binding var selectedTag: String?
var body: some View {
Button(action: {
self.selectedTag = self.productTag
})
}
}
with viewmodel (but not working for me - UI is not updating)
struct MainView: View {
@State private var selectedTag: String?
var body: some View {
VStack {
ForEach(products, id: \.description) { item in
SubView(viewModel: SubViewViewModel(productTag: item.productId ?? "", selectedTag: self.selectedTag ?? ""))
}
}
}
}
struct SubView: View {
private var viewModel: SubViewViewModel
var body: some View {
Button(action: {
viewModel.selectedTag = viewModel.productTag
})
}
}
class SubViewViewModel: ObservableObject {
var productTag: String
@Published var selectedTag: String?
init(productTag: String, selectedTag: String) {
self.productTag = productTag
self.selectedTag = selectedTag
}
}
I might missing some concept, kindly suggest the solution for same.