如何告诉SwiftUI视图绑定到嵌套的ObservableObjects [英] How to tell SwiftUI views to bind to nested ObservableObjects

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

问题描述

我有一个SwiftUI视图,其中包含一个名为appModel的EnvironmentObject.然后,它在其body方法中读取值appModel.submodel.count.我希望这会将我的视图绑定到submodel上的属性count,以便在属性更新时重新呈现,但这似乎不会发生.

I have a SwiftUI view that takes in an EnvironmentObject called appModel. It then reads the value appModel.submodel.count in its body method. I expect this to bind my view to the property count on submodel so that it re-renders when the property updates, but this does not seem to happen.

这是一个错误吗?如果没有,那么将视图绑定到SwiftUI中环境对象的嵌套属性的惯用方式是什么?

Is this a bug? And if not, what is the idiomatic way to have views bind to nested properties of environment objects in SwiftUI?

具体来说,我的模型是这样的...

Specifically, my model looks like this...

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

class AppModel: ObservableObject {
  @Published var submodel: Submodel = Submodel()
}

我的观点看起来像这样...

And my view looks like this...

struct ContentView: View {
  @EnvironmentObject var appModel: AppModel

  var body: some View {
    Text("Count: \(appModel.submodel.count)")
      .onTapGesture {
        self.appModel.submodel.count += 1
      }
  }
}

当我运行应用程序并单击标签时,count属性的确会增加,但标签不会更新.

When I run the app and click on the label, the count property does increase but the label does not update.

我可以通过将appModel.submodel作为属性传递给ContentView来解决此问题,但我希望避免这样做.

I can fix this by passing in appModel.submodel as a property to ContentView, but I'd like to avoid doing so if possible.

推荐答案

嵌套模型在SwiftUI中尚不可用,但是您可以执行以下操作

Nested models does not work yet in SwiftUI, but you could do something like this

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

class AppModel: ObservableObject {
    @Published var submodel: SubModel = SubModel()
    
    var anyCancellable: AnyCancellable? = nil
    
    init() {
        anyCancellable = submodel.objectWillChange.sink { [weak self] (_) in
            self?.objectWillChange.send()
        }
    } 
}

基本上,您的AppModelSubModel捕获事件,并将其进一步发送到View.

Basically your AppModel catches the event from SubModel and send it further to the View.

如果不需要SubModel上课,则可以尝试以下类似方法:

If you do not need SubModel to be class, then you could try something like this either:

struct SubModel{
    var count = 0
}

class AppModel: ObservableObject {
    @Published var submodel: SubModel = SubModel()
}

这篇关于如何告诉SwiftUI视图绑定到嵌套的ObservableObjects的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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