在我为此失去理智之前。有人请告诉我,为什么它不起作用。我已经花了几个小时来尝试完成这项工作。ObservedObject 只是拒绝更新我的视图。
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")
}
}