我想使用 SwfitUI 在 macOS 上制作一些应用程序。
继iOS之后,还有SceneDelegate
(iOS 13之后)。但在 macOS 中,只有 AppDelegate
。
好的。我想在 SceneDelegate
的 scene
方法上使用 environmentObject
window.rootViewController = UIHostingController(rootView: contentView
.environmentObject(mainController)
)
在我的ContentView
中使用@EnvironmentObject
属性包装器。
实际上我无法实现 .environmentObject()
因为 macOS 中没有 SceneDelegate
!
如何解决这个问题?
最佳答案
这是为 macOS SwiftUI 项目默认生成的 AppDelegate,以及如何为其中的内容 View 设置环境对象。
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create content view
let contentView = ContentView().environmentObject(AppSettings())
// Create the window and set the content view.
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 800, height: 600),
styleMask: [.titled, .closable, .miniaturizable],
backing: .buffered, defer: false)
window.center()
window.setFrameAutosaveName("Main Window")
window.contentView = NSHostingView(rootView: contentView)
window.makeKeyAndOrderFront(nil)
window.autorecalculatesKeyViewLoop = true
}
关于swift - macOS 上的 EnvironmentObject 和 SceneDelegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114617/