如何告诉SwiftUI视图绑定到多个嵌套的ObservableObject [英] How to tell SwiftUI views to bind to more than one nested ObservableObject

查看:328
本文介绍了如何告诉SwiftUI视图绑定到多个嵌套的ObservableObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在另一个类中嵌套了两个类,这是SwiftUI视图中的一个可观察对象.即使嵌套类中的属性声明为@Published,但它们的值(当它们更改时)不会在主视图中更新.

I have two classes nested in another class, which is an observable object in a SwiftUI view. Even though properties in the nested classes are declared as @Published, their values (when they change) do not update in the main view.

这里提出了一个类似的问题,我可以用它来使它适用于两个子类之一,但不能同时适用于这两个子类.

A similar question has been asked here, and I could use it to get it to work for one of the two subclasses, but not both.

如何告诉SwiftUI视图绑定到嵌套ObservableObjects

这是模型:

class Submodel1: ObservableObject {
  @Published var count = 0
}

class Submodel2: ObservableObject {
  @Published var count = 0
}

class Model: ObservableObject {
  @Published var submodel1: Submodel1 = Submodel1()
  @Published var submodel2: Submodel2 = Submodel2()
}

这是主视图:

struct ContentView: View {
  @ObservedObject var model: Model = Model()

  var body: some View {
    VStack {
      Text("Count: \(model.submodel1.count)")
        .onTapGesture {
          self.model.submodel1.count += 1
        }
      Text("Count: \(model.submodel2.count)")
        .onTapGesture {
          self.model.submodel2.count += 1
        }
    }
  }
}

将其添加到模型类(请参见前面的Stackoverflow问题)可用于更新submodel1的更改,但不能同时更新:

Adding this to the model class (see previous Stackoverflow question) works for updating on submodel1 changes, but not both:

  var anyCancellable: AnyCancellable? = nil
  init() {
      anyCancellable = submodel1.objectWillChange.sink { (_) in
          self.objectWillChange.send()
      }
   }

我要寻找的是一种将submodel1和submodel2的更改都传递给我的视图的方法.

What I'm looking for is some way to pass on changes of both the submodel1 and submodel2 to my view.

推荐答案

您可以使用 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆