微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

基于文档的应用程序,如何从菜单中访问文档?

如何解决基于文档的应用程序,如何从菜单中访问文档?

我正在Xcode 12中使用新的MultiPlatform SwiftUI文档模板,但我不明白如何从菜单项中访问当前的FileDocument。

我的应用代码如下(直接来自模板)。

@main
struct MyApp: App {
    var body: some Scene {
        DocumentGroup(newDocument: MyDocument()) { file in
            ContentView(document: file.$document)
        }
        .commands {
            CommandMenu("Utilities") {
                Button(action: {
                    // How to get access to the current FileDocument ?
                }) {
                    Text("Test")
                }
            }
        }
    }
}

解决方法

您可以创建一个 FocusedValueKey,从您的内容视图发布到文档的绑定,然后使用 @FocusedBinding 在菜单中观察它。有一个很好的解释here

,

这里是可能方法的演示。想法是使用应用程序状态对象将当前文档存储在其中,并从所需的任何位置进行访问。

通过Xcode 12 / iOS 14测试

@main
struct MyApp: App {
    @StateObject var appState = AppState()

    var body: some Scene {
        DocumentGroup(newDocument: MyDocument()) { file in
            createView(for: file)
        }
        .commands {
            CommandMenu("Utilities") {
                Button(action: {
                    if let doc = appState.currentDocument {
                        // do something
                    }
                }) {
                    Text("Test")
                }
            }
        }
    }

    private func createView(for file: FileDocumentConfiguration<MyDocument>) -> some View {
        appState.currentDocument = file.document
        return ContentView(document: file.document)
    }
}

class AppState: ObservableObject {
    @Published var currentDocument: MyDocument?
}
,

为了回答我自己的问题,我就是这样解决的。您可以通过组合从 .commands 部分发送信号。

@main
struct MyApp: App {

    private let exportAsImage = PassthroughSubject<Void,Never>()

    var body: some Scene {
        DocumentGroup(newDocument: MyDocument()) { file in
            ContentView(document: file.$document)
                .onReceive(exportAsImage) { _ in
                    file.document.exportAsImage()
                }
        }
        .commands {
            CommandGroup(replacing: .importExport) {
                Button(action: {
                    exportAsImage.send()
                }) {
                    Text("Export as Image...")
                }
            }
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。