简体   繁体   中英

@ObservedObject does not get updated on updating the array

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM