gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:33:01 24 4
gpt4 key购买 nike

是否有纯 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com