macOS SwiftUI:在文档应用程序中实例化新的非文档窗口 [英] macOS SwiftUI: Instantiate new non-document window in document app
问题描述
有没有纯 SwiftUI 的方式来打开新窗口?我有一个基于文档的应用程序,它的应用程序看起来像这样:
Is there a pure-SwiftUI way to open a new window? I have a sorta-working document-based app whose app looks like this:
@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 {
...
}
}
...
}
现在我想添加一个菜单命令来在它自己的窗口中实例化一个小的自包含实用工具.到目前为止,我在网上看到的任何讨论实际上都涉及使用 NSHostingView
作为其内容视图制作一个新的 NSWindow
.这似乎不太像 SwiftUI,鉴于他们最近添加的 DocumentGroup
和 WindowGroup
似乎是一个很大的疏忽.
Now I want to add a menu command to instantiate a little self-contained utility tool in its own window. So far any discussion I see online actually involves making a new NSWindow
with an NSHostingView
as its content view. This seems not very SwiftUI-ish, and given their recent additions of DocumentGroup
and WindowGroup
seems like a pretty big oversight.
我尝试将 WindowGroup
放在应用程序的场景中,但如果我注释掉 DocumentGroup
,它只会显示我的窗口.
I tried putting a WindowGroup
in the app’s scene, but it only shows my window if I comment out the DocumentGroup
.
推荐答案
我们需要一个 WindowGroup
作为一个窗口,所以第一步/简单的步骤就是添加它,比如
We need a WindowGroup
for a window, so the first/simple step is just to add it, like
(使用 Xcode 12.5/macOS 11.3 创建的演示,基于 Document App 模板)
(Demo created with Xcode 12.5 / macOS 11.3, based on Document App template)
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>获得它.新建
菜单
如果我们想从其他地方以编程方式创建/显示它,比如通过命令,我们可以使用基于 URL 的方法,例如
If we want to create/show it programmatically from other place, say via commands, we can use URL-based approach, like
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"))
}
}
}
这篇关于macOS SwiftUI:在文档应用程序中实例化新的非文档窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!