SwiftUI:如何查看带有数组属性的类型对象的EnvironmentObject的更改? (EO->属性->类->属性)

时间:2020-09-14 13:14:24

标签: swift xcode swiftui

“我的列表”将显示“商店状态”类的初始状态。对于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())
    }
}

0 个答案:

没有答案