我们如何在onChange / onReceive中使用ObservableObject?

时间:2020-11-03 20:40:14

标签: swiftui

我有这段代码,其中包含一个struct和ObservableObject。我用一些按钮喂我的ObservableObject。 我正在尝试对我的ObservableObject进行任何更改来运行一些打印文件,它应该可以正常工作,但是我不知道自己缺少什么。

PS:另外我想知道我应该使用.onChange还是.onReceive进行这项工作?

    struct Data: Identifiable
{
    let id  = UUID()
    var name: String
}

let dataTrain1 = [Data(name: "A"), Data(name: "A"), Data(name: "A"), Data(name: "A"), Data(name: "A")]
let dataTrain2 = [Data(name: "A"), Data(name: "B"), Data(name: "B"), Data(name: "A"), Data(name: "A")]


class DataModel: ObservableObject
{
    @Published var items: [Data] = []
}




struct ContentView: View
{
    
    
    @StateObject var dataModel = DataModel()
    
    var body: some View
    {
        
        
        
        ZStack
        {
            
            VStack
            {
                HStack
                {
                    
                    Button("Load dataTrain1") { dataModel.items = dataTrain1 }
                    
                    Spacer()
                    
                    Button("Load dataTrain2") { dataModel.items = dataTrain2 }
                    
                }
                .padding(.horizontal)
                
                Spacer()
            }
            
            HStack
            {
                ForEach(dataModel.items) { item in
                    
                    Text(item.name)
                        .font(.title)
                        .bold()
                        .foregroundColor(item.name == "A" ? Color.red : Color.blue)
                    
                }
 
            }
  
        }
        .onChange(of: dataModel.items) { _ in print("dataModel Changed!") } // ← Here
        .onReceive(dataModel.$items) { _ in print("dataModel Changed!") } // ← Here
        
        
    }
    
}

1 个答案:

答案 0 :(得分:1)

要使用onChange,您的Data必须符合Equatable

struct Data: Identifiable, Equatable { ... }