如何从SwiftUI视图呈现UIDocumentInteractionController

问题描述

我有以下代码,其中包含SwiftUI视图的屏幕截图,并且我想在UIDocumentInteractionController中呈现此屏幕截图。我已经在UIKit ViewController中完成了此操作,我想知道是否有一种方法可以将我必须使用的非工作代码转换为可以呈现UIDocumentInteractionController的代码

import SwiftUI

struct ContentView: View {
    let documentInteractionController = UIDocumentInteractionController()
    var body: some View {
        vstack {
            SharableView()
            Button(action: {
                let vc = UIHostingController(rootView: SharableView())
                vc.view.frame = CGRect(x: 0,y: 0,width: 400,height: 400)
                if let screenshot = vc.view.makeSnapshot() {
                    if let data = screenshot.pngData() {
                        let filename = getDocumentsDirectory().appendingPathComponent("ScreenShot.png")
                        try? data.write(to: filename)
                        documentInteractionController.uti = "public.image"
                        documentInteractionController.url = filename
                        documentInteractionController.presentOptionsMenu(from: vc.view.bounds,in: vc.view,animated: true)
                    }
                }
            },label: {
                Text("Share")
            })
        }
    }
}

struct SharableView: View {
    var body: some View {
        Text("Hello,world!")
            .padding()
    }
}

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask)
    return paths[0]
}

extension UIView {
    func makeSnapshot() -> UIImage? {
        let renderer = UIGraphicsImageRenderer(size: frame.size)
        return renderer.image { _ in drawHierarchy(in: bounds,afterScreenUpdates: true) }
    }
}

这给了我一个合理的错误。但是我不知道如何解决它。传递给documentInteractionController.presentOptionsMenu(...)的正确参数是什么?

[Presentation] Attempt to present <_UIDICActivityViewController: 0x7f84e1024400> on <_TtGC7SwiftUI19UIHostingControllerV9testShare12SharableView_: 0x7f84e2906d70> (from <_TtGC7SwiftUI19UIHostingControllerV9testShare12SharableView_: 0x7f84e2906d70>) whose view is not in the window hierarchy.

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...