swift - macOS 上的 EnvironmentObject 和 SceneDelegate

标签 swift macos swiftui

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

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

好的。我想在 SceneDelegatescene 方法上使用 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/

相关文章:

swift - 基于值的Alamofire参数

ios - SpriteKit SKPhysicsBody splinter 的碰撞

macos - 即使有 bin 文件夹,Subl 也不会在终端中打开

swift - 如何使用 SwiftUI 将 VStack 在 List 内水平居中?

SwiftUI - 如果在 ForEach 循环中

ios - 如何扫描字符串,识别并转换为 NSURL

swift - 用于 nil 过滤的通用 Swift 字典扩展

ios - 是否有关于OSX和/或IOS编程的播客 channel ?

python - 尝试在 Mac OS X 上设置 Enthought enpkg 时出现钥匙串(keychain)问题

SwiftUI 有条件地渲染一个 View 或另一个 View