ios - 如何从 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.
解决方案
推荐阅读
- java - 将属性加载到 InputStream
- javascript - 情绪和不和谐的反应
- ruby-on-rails - Rails 5.2.1 - 模型和片段缓存
- php - Laravel 4.2 走错路了
- powershell - 无法通过 Powershell 找到证书:驱动器或证书提供程序
- aerospike - 在没有索引的情况下看到具有 4G 的 memory_used_index_bytes
- c# - 在 Roslyn Fixer 中获取样式设置
- sql-server - BCP 实用程序 - 忽略导入文件中的默认值
- javascript - 用于添加到购物车的 redux concat 数组
- python - 使用两个或多个不同的键查找 django 模型