swiftui - macOS SwiftUI : Instantiate new non-document window in document app

标签 swiftui macos-big-sur

是否有纯 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作为其内容 View 。这似乎不是很像 SwiftUI,并且考虑到他们最近添加的 DocumentGroupWindowGroup似乎是一个很大的疏忽。
我试着放一个 WindowGroup在应用程序的场景中,但如果我注释掉 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 获得它菜单
demo
如果我们想从其他地方以编程方式创建/显示它,比如通过命令,我们可以使用基于 URL 的方法,比如
demo2
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"))
        }
    }
}
demo3

关于swiftui - macOS SwiftUI : Instantiate new non-document window in document app,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67363210/

相关文章:

ios - 更新 SwiftUI 导航栏标题

macos - 无法使用应用 Proxifier : protocol wrong type for socket 监听 macOS Big Sur 上的任何 TCP 端口

java - 如何在 Big Sur 上更改我的 JDK 版本?

javascript - expressGraphQL 不是函数

swiftui - 在 SwiftUI 上下文中,单一事实来源 (SSOT) 的含义是什么?

ios - 在 SwiftUI 中使用谷歌登录时来自 OIDAuthorizationService 的 NSInvalidArgumentException

google-cloud-platform - 在Apple Silicon/Big Sur上安装Google Cloud SDK时出现anthoscli错误

python - 无法在MacOS上的python中导入opengl.gl

ios - 如何在 swiftui 邮件应用程序中传递主题和正文文本?

ios - 从 WidgetKit WidgetKit 扩展检测应用程序启动