如何以编程方式显示DocumentGroup?解决关闭后无法重开问题
解决SwiftUI中DocumentGroup关闭后无法重新打开的问题
SwiftUI里WindowGroup可以通过ID用openWindow(id:)重新唤起,但DocumentGroup没有这个参数,关闭后没法通过常规方式编程打开。下面分平台给出解决方案:
macOS 平台
直接用AppKit的NSDocumentController——这是DocumentGroup底层依赖的系统控制器,调用它的方法就能直接唤起文档窗口:
// 触发打开新文档窗口 func openNewDocument() { NSDocumentController.shared.newDocument(nil) } // 打开已有文档(弹出文件选择器) func openExistingDocument() { NSDocumentController.shared.openDocument(nil) }
在SwiftUI视图里直接调用即可,比如给按钮加点击事件:
Button("新建文档") { openNewDocument() }
iPadOS 平台
iPadOS用场景激活API来唤起文档场景:
import UIKit func openDocumentScene() { // 请求激活新的文档场景,没有的话会自动创建 UIApplication.shared.requestSceneSessionActivation(nil, userActivity: nil, options: nil, errorHandler: nil) }
如果要精准定位已存在的文档场景,可以过滤场景类型:
func openExistingDocumentScene() { let documentScenes = UIApplication.shared.connectedScenes.filter { $0.session.role == .windowApplication && $0.configuration.name == "DocumentConfiguration" } if let scene = documentScenes.first as? UIWindowScene { UIApplication.shared.requestSceneSessionActivation(scene.session, userActivity: nil, options: nil, errorHandler: nil) } else { openDocumentScene() } }
跨平台封装
可以写个工具类统一处理,不用区分平台:
import SwiftUI enum DocumentOpener { static func newDocument() { #if os(macOS) NSDocumentController.shared.newDocument(nil) #elseif os(iOS) UIApplication.shared.requestSceneSessionActivation(nil, userActivity: nil, options: nil, errorHandler: nil) #endif } static func existingDocument() { #if os(macOS) NSDocumentController.shared.openDocument(nil) #endif } }
调用示例:
Button("新建文档") { DocumentOpener.newDocument() }
内容的提问来源于stack exchange,提问作者Viktor Maric
相关产品推荐
相关产品推荐

