为什么嵌套发布者不在 SwiftUI/Combine 中调用我的自定义发布者?

问题描述

这是How to share published model between two view models in SwiftUI?的后续问题。

为了使嵌套的已发布模型真正发布,我使用了此处描述的方法How to tell SwiftUI views to bind to nested ObservableObjects。到目前为止一切顺利,手动 objectwillChange 传递有效,并且父视图模型正在发布更改。

但是,如果我尝试使用自定义发布者,这些发布者利用已发布的嵌套模型,它们的功能将不会像我习惯的那样(具有常规发布的属性)。这是一个简化的例子。

我错过了什么吗?

var viewport = {
    width: 'undefined',height: 'undefined',ratio: 1.6
};

var bg_1280x720 = {
    name: 'RZ_BG_1280x720_16-9.png',width: '1280',height: '720',ratio: 1.7
};

var bg_1920x1080 = {
    name: 'RZ_BG_1280x720_16-9.png',ratio: 1.7
};

var bg_2000x2000 = {
    name: 'RZ_BG_2000x2000_1-1.png',width: '2000',height: '2000',ratio: 1
};

bgOverlays = [
bg_1280x720,bg_1920x1080,bg_2000x2000
]

// I need a script,that looks at: "viewport.ratio" and then looks at the ".ratio: values" of all the objects in: "bgOverlays" and then creates a new array that has only the objects in it,that are closest to: "viewport.ratio",in terms of their: ".ratio: value".

// example:
// viewport.ratio = 1.1     output: newArray[bg_2000x2000]
// viewport.ratio = 2           output: newArray[bg_1280x720,bg_1920x1080]
//well here you go :)

var low=bgOverlays
  .map(a=>Math.abs(a.ratio-viewport.ratio))
  .sort((a,b)=>a-b)[0]

var newArray=bgOverlays
  .filter(a=>Math.abs(a.ratio-viewport.ratio)==low)
console.log(newArray)

感谢您的支持

解决方法

也许我没有抓住重点,但您不能只使用计算属性吗?

class ContentViewModel: ObservableObject {
    @Published var model = Model()

    var isToggled: Bool { model.nestedIsToggled }
}