首页 > 解决方案 > macOS 上的 EnvironmentObject 和 SceneDelegate

问题描述

我想使用 SwfitUI 在 macOS 上制作一些应用程序。

在 iOS 之后,还有SceneDelegate(iOS 13 之后)。但在 macOS 中,只有AppDelegate.

好的。我想用environmentObjectonSceneDelegatescene方法

window.rootViewController = UIHostingController(rootView: contentView
            .environmentObject(mainController)
        )

@EnvironmentObject我的ContentView.

从字面上看,我无法.environmentObject()在 macOS 中实现因为没有SceneDelegate

我怎么解决这个问题?:(

请帮忙

标签: swiftmacosswiftui

解决方案


这是为 macOS SwiftUI 项目默认生成的 AppDelegate,以及如何为其中的内容视图设置环境对象。

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
}

推荐阅读