在 SwiftUI DocumentGroup macOS 中创建并打开新文档

Rya*_*yan 8 macos swiftui documentgroup

如何在基于 SwiftUI ReferenceFileDocument 的应用程序中打开新文档窗口?

背景

此 macOS 应用程序WindowGroups使用.handleEvents(:). 不幸的是,这会导致文件/新建菜单将这些窗口组的名称包含在“新建...窗口”中(如图所示)。由于未能找到一种方法来覆盖该包装,我尝试仅使用CommandGroup(replacing: .newItem) {}.

然而,我也未能重新制作“创建并打开新文档窗口”命令。我尝试过搜索一些要发布并申请的通知.handleEvents。这只会使现有打开的文档窗口成为关键窗口。如果没有打开的文档,它什么也不做。

不需要的包裹

在此输入图像描述

@main
struct TheApp: App {
    
    @StateObject var root: RootStore
    
    var body: some Scene {
        DocumentGroup { ProjectDocument() } editor: { doc in
            DocumentGroupRoot(...)
        }.commands { Menus(root: root) }
        
        WindowGroup("Preset Color Maps") {
             ... .handlesExternalEvents(matching: ...) /// Allows multiple windows
        }.handlesExternalEvents(matching: ...)
        
        WindowGroup("Tutorial") {
             ...
        }.handlesExternalEvents(matching: ...)
    }
}
Run Code Online (Sandbox Code Playgroud)

卡在“新项目”更换接线上

在此输入图像描述

struct NewCommands: Commands {
    var body: some Commands {
        CommandGroup(replacing: .newItem) {
            NewProjectButton()
        }
        
        CommandGroup(after: .newItem) {
            ImportersButtons()
        }
    }

    private struct NewButton: View {
        
        @Environment(\.openURL) var openURL
        
        var body: some View {
            Button("New Project") { openURL(ExternalEvents.new.url) }
                .keyboardShortcut("n", modifiers: .command)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
@main
struct TheApp: App {
    
    @StateObject var root: RootStore
    
    var body: some Scene {
        DocumentGroup { ProjectDocument() } editor: { doc in
            DocumentGroupRoot(...)
                .handlesExternalEvents(...) /// Doesn't enable new doc windows
        }.commands { Menus(root: root) }
         .handlesExternalEvents(matching: ...) /// Only makes existing doc key window
        
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

Rya*_*yan 10

好吧,经典。发帖然后解决了。解决方案只是返回共享的 NSDocumentController 并请求一个新文档。我会在角落里脸红。

Button("New Project") {
      NSDocumentController.shared.newDocument(nil)
}
Run Code Online (Sandbox Code Playgroud)