“我的列表”将显示“商店状态”类的初始状态。对于CarState,我将展示(梅赛德斯,保时捷,BWM)。对于我的PersonState,它将显示(Max,Dieter)。但是,如果单击“按钮”,则“状态类”的items数组将更改,但是我的“视图(列表)”不会更新或更改。 我的View如何收听子项目?
import Foundation
import SwiftUI
struct Car: Codable, Identifiable {
var id = UUID()
var brand: String
}
struct Person: Codable, Identifiable {
var id = UUID()
var name: String
}
class CarState: ObservableObject {
@Published private(set) var items: [Car] = [
Car(brand: "Mercedes"),
Car(brand: "Porsche"),
Car(brand: "BWM")
]
func next() {
items = [
Car(brand: "Renault"),
Car(brand: "Audi")
]
}
}
class PersonState: ObservableObject {
@Published private(set) var items: [Person] = [
Person(name: "Max"),
Person(name: "Dieter")
]
func next() {
items = [
Person(name: "Hansi"),
Person(name: "Vogel")
]
}
}
class Store: ObservableObject {
@Published private(set) var carState: CarState
@Published private(set) var personState: PersonState
init() {
carState = CarState()
personState = PersonState()
}
func nextCars() {
carState.next()
}
func nextPersons() {
personState.next()
}
}
struct ContentView: View {
@EnvironmentObject var store: Store
var body: some View {
VStack {
Button(action: {
print("LOAD NEXT TRIGGERED")
store.carState.next()
store.personState.next()
}) {
Text("LOAD NEXT")
}
Divider()
List {
ForEach(store.carState.items) { item in
Text(item.brand)
}
}
.listStyle(PlainListStyle())
.animation(.easeIn)
Divider()
List {
ForEach(store.personState.items) { item in
Text(item.name)
}
}
.listStyle(PlainListStyle())
.animation(.easeIn)
Spacer()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(Store())
}
}