Here is a simple representation of what I'm trying to do. I need to have a view updated when values change in a class stored inside a published var. This ContentView
should be updated when Items
is updated in the ItemManager
stored in the state of the ContentViewViewModel
.
The ContentView
with the ForEach well display the Item
stored in the array, but if I store the array of Item
in the ContentViewState
the view is updated correctly so why can't I move the data and logic attach to it in a subclass?
struct ContentView: View {
@ObservedObject private var viewModel = ContentViewViewModel()
var body: some View {
VStack {
ForEach(viewModel.state.itemManager.items, id: \.id) { item in
Text(item.value)
}
Button("Add Item") {
viewModel.triggerAddButton()
}
}
}
}
class ContentViewViewModel: ObservableObject {
@Published var state = ContentViewState()
func triggerAddButton() {
state.itemManager.addItem()
}
}
struct ContentViewState {
let itemManager = ItemManager()
}
class ItemManager: ObservableObject {
@Published var items: [Item] = [Item("Item 1"), Item("Item 2")]
func addItem() {
items.append(.init("NewItem"))
}
}
struct Item: Identifiable {
var id: UUID
var value: String
init(_ value: String) {
self.value = value
self.id = UUID()
}
}