macOSSwiftUI:在文档应用程序中实例化新的非文档窗口

有没有一种纯 SwiftUI 的方式来打开一个新窗口?我有一个基于文档的应用程序,它的应用程序看起来像这样:

@main struct MyApp: App
{
    var
    body: some Scene {
        DocumentGroup(newDocument: ProjectDocument.init) { inGroup in
            ProjectWindowContentView(document: inGroup.document)
                .frame(minWidth: 301.0, minHeight: 100.0)
                .onReceive(self.addTerrainGeneratorLayerCommand) { _ in
                    inGroup.document.addTerrainGeneratorLayer()
                }
        }
        .commands {
            ...
        }
    }
    ...
}

现在我想添加一个菜单命令来在它自己的窗口中实例化一个小的自包含实用工具。到目前为止,我在网上看到的任何讨论实际上都涉及创建一个新NSWindowNSHostingView内容视图。这似乎不是很像 SwiftUI,而且考虑到他们最近添加的DocumentGroup并且WindowGroup似乎是一个很大的疏忽。

我尝试将 aWindowGroup放入应用程序的场景中,但如果我注释掉DocumentGroup.

回答

我们需要一个WindowGroup窗口,所以第一步/简单的步骤就是添加它,比如

(使用 Xcode 12.5 / macOS 11.3 创建的演示,基于 Document App 模板)

struct PlayDocumentXApp: App {
    var body: some Scene {
        DocumentGroup(newDocument: PlayDocumentXDocument()) { file in
            ContentView(document: file.$document)
        }
        WindowGroup("Tools") {
            Text("This is tool window")
                .frame(width: 200, height: 400)
        }
    }
}

我们通过File > New菜单提供

如果我们想从其他地方以编程方式创建/显示它,比如通过命令,我们可以使用基于 URL 的方法,比如

struct PlayDocumentXApp: App {
    var body: some Scene {
        DocumentGroup(newDocument: PlayDocumentXDocument()) { file in
            ContentView(document: file.$document)
        }
        .commands {
            CommandMenu("Test") {
                Button("Show Tools") {
                    NSWorkspace.shared.open(URL(string: "myTools://my")!)
                }
            }
        }
        WindowGroup("Tools") {
            Text("This is tool window")
                .frame(width: 200, height: 400)
                .handlesExternalEvents(preferring: Set(arrayLiteral: "myTools://my"), allowing: Set(arrayLiteral: "myTools://my"))
        }
    }
}


以上是macOSSwiftUI:在文档应用程序中实例化新的非文档窗口的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>