Before I lose my mind over this. May someone please tell me, why it is not working. I am already hours in trying to make this work. ObservedObject just refuses to update my view.
struct ContentView: View {
@ObservedObject var viewModel = ListViewModel()
var body: some View {
NavigationView {
List(){
ForEach(viewModel.items, id:\.self) { item in
Text(item)
}
}
.navigationBarTitle("Test List", displayMode: .inline)
.navigationBarItems(
trailing: Button(action: { ListViewModel().addItem()}) { Image(systemName: "info.circle")}.accentColor(.red))
}
}
}
class ListViewModel: ObservableObject, Identifiable {
@Published var items: Array<String> = ["1", "2", "3", "4", "5","6"]
func addItem(){
items.append("7")
}
}
You're creating a new ListViewModel by using an initializer (ListViewModel()
) in your button action.
Instead, refer to the one that you've set up as property in your view: viewModel.addItem()