我有以下代码截取 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.