0

当通知到达数据更改时,我想触发 swiftUI List UI 更新。这是我的代码:

class MyModel: ObservableObject {
     @Published var contracts: [String] = ["Good"]

     init(contracts: [String]) {
        self.contracts = contracts
     }

     func updateContracts() {
        self.contracts.append("good")
     }

}


struct MyView: View {

    @ObservedObject var myModel = MyModel(contracts: ["Good", "Morning"])

    var body: some View {
        List {
            ForEach(myModel.contracts, id: \.self) { data in
                Text(data)
            }
        }
    }
}

另一个地方的通知部分是:

NotificationCenter.default.addObserver(self, selector: #selector(modelsUpdated), name: NSNotification.Name(rawValue: kxxxxUpdate), object: nil)

 @objc func modelsUpdated(notification: Notification) {
     MyView().myModel.updateContracts()
}

如果我将此通知部分移动到MyModel类中,则 updateContracts()直接在modelsUpdatedUI 中调用会更新。

代码是:

    class MyModel: ObservableObject {
           
         @Published var contracts: [String] = ["G
    
    ood"]
        

         init(contracts: [String]) {
               self.contracts = contracts
               NotificationCenter.default.addObserver(self, selector: #selector(modelsUpdated), name: NSNotification.Name(rawValue: kxxxxUpdate), object: nil)
            
         }

         func updateContracts() {
            self.contracts.append("good")
         }

         @objc func modelsUpdated(notification: Notification) {
              updateContracts() // works
         }
    
    }

有谁知道为什么?谢谢!

编辑

MyView()以上只是为了说明是 的一个实例MyView,它是屏幕上的一个实例。

4

1 回答 1

0

当您调用 MyView().myModel.updateContracts() 您创建视图的新实例,这与您正在显示的不同。

于 2020-10-12T08:33:15.527 回答