Hi!
Based on stackoverflow I wanted to get information about the Window frame back into a SwiftUI View on macOS.
So I added the environmentObject:
let contentView = ContentView()
.environmentObject(windowInfo)
into AppDelegate.swift -> func applicationDidFinishLaunching and added the EnvironmentObject:
struct ContentView: View {
@EnvironmentObject var windowInfo: WindowInfo
var body: some View {
Text("windowInfo: \(windowInfo.frame.debugDescription)")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
Unfortunately this does not work. I get the error
MissingEnvironmentObjectError: Missing EnvironmentObject
EnvironmentObject crashed due to missing environment of type: WindowInfo. To resolve this add `.environmentObject(WindowInfo(...))` to the appropriate preview.
Pay attention to the error message. It specifically mentions the word "preview", which means you are experiencing this issue when using an Xcode preview. You should've mentioned this in your question. When you preview a view (in this case, ContentView), only that view and all of its subviews are invoked; your app delegate is not involved at all. For a preview, the entry point is the previews property. It's within that property that you must inject your environment objects. Don't make windowInfo global; that's bad practice. Instead, declare it as a StateObject in your preview provider:
struct ContentView_Previews: PreviewProvider {
@StateObject static var windowInfo = WindowInfo()
static var previews: some View {
ContentView()
.environmentObject(windowInfo)
}
}