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

查看:21
本文介绍了如何告诉 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天全站免登陆