[英]Make SwiftUI document available as EnvironmentObject
我正在使用FileDocument
读取文件文档。 该文档可通过绑定到最顶层视图获得:
struct ContentView: View {
@Binding var document: SomeDocument
var body: some View {
Text(self.document.someString)
NestedChildViews().environmentObject(self.document)
}
}
有没有办法将文档的@Binding
转换为@EnvironmentObject
以使其可用于所有嵌套视图? 简单地用@Binding
@EnvironmentObject
行不通的,因为FileDocument
是一个结构。
Property type 'SomeDocument' does not match that of the 'wrappedValue' property of its wrapper type 'EnvironmentObject'
在ContentView
中创建作为@StateObject
创建的中间ObservableObject
将不起作用,因为它必须在 Binding to document 可用之前启动:
struct ContentView: View {
@Binding var document: SomeDocument
@StateObject var sharedState = SomeSharedState(document: self.document) // won't work
}
在文档和一系列嵌套视图之间不传递所有级别之间的绑定的最佳方法是什么?
您应该在视图的 init 中初始化@StateObject
,因为您将document
传递到 init 中:
struct ContentView: View {
@Binding var document: SomeDocument
@StateObject var sharedState: SomeSharedState
init(document: Binding<SomeDocument>) {
_document = document
_sharedState = StateObject(wrappedValue: SomeSharedState(document: document.projectedValue))
}
var body: some View {
Text(document.someString)
.environmentObject(sharedState)
/* TEST TO SHOW IT WORKS
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
document = SomeDocument(someString: "New!")
}
}
*/
}
}
class SomeSharedState: ObservableObject {
@Published var document: Binding<SomeDocument>
init(document: Binding<SomeDocument>) {
_document = Published(initialValue: document)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.