【问题标题】:Create and open a new document in SwiftUI DocumentGroup macOS在 SwiftUI DocumentGroup macOS 中创建并打开一个新文档
【发布时间】:2021-05-07 22:27:30
【问题描述】:

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

背景

此 macOS 应用程序使用 .handleEvents(:) 以编程方式打开 WindowGroups。不幸的是,这会导致文件/新建菜单将这些窗口组的名称包含在“新建...窗口”中(如图所示)。由于无法找到覆盖该包装的方法,我尝试完全使用 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: ...)
    }
}

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

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)
        }
    }
}
@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
        
        ...
    }
}

【问题讨论】:

    标签: macos swiftui documentgroup


    【解决方案1】:

    好的,经典。贴出来然后解决。解决方案只是回到共享的 NSDocumentController 并要求一个新文档。我会在角落里脸红。

    Button("New Project") {
          NSDocumentController.shared.newDocument(nil)
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      • 2015-05-03
      • 2011-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多