我正在阅读FileDocument
使用 SwiftUI。该文档可通过绑定到最顶层视图获得:
struct ContentView: View {
@Binding var document: SomeDocument
var body: some View {
Text(self.document.someString)
NestedChildViews().environmentObject(self.document)
}
}
有没有办法将@Binding
文档的 this 转换为 an@EnvironmentObject
以使其可用于所有嵌套视图?简单地替换@Binding
with是@EnvironmentObject
行不通的,因为FileDocument
是一个结构。
Property type 'SomeDocument' does not match that of the 'wrappedValue' property of its wrapper type 'EnvironmentObject'
创建一个作为内部创建的中间ObservableObject
是行不通的,因为它必须在 Binding to document 可用之前启动:@StateObject
ContentView
struct ContentView: View {
@Binding var document: SomeDocument
@StateObject var sharedState = SomeSharedState(document: self.document) // won't work
}
在文档和一系列嵌套视图之间不传递所有级别之间的绑定的最佳方法是什么?