【发布时间】:2019-12-02 02:39:16
【问题描述】:
我正在尝试将 SwiftUI 视图呈现为 UIImage,然后让用户选择保存到相机胶卷或通过电子邮件发送给其他人。
例如,我想将 50 行的列表渲染到 UIImage 中。
struct MyList: View {
var body: some View {
List {
ForEach(0 ..< 50, id:\.self) {
Text("row \($0)")
}
}
}
}
过去几周在互联网上搜索仍然没有运气。我尝试了 2 种不同的方法。
1. UIHostingController (source here)
let hosting = UIHostingController(rootView: Text("TEST"))
hosting.view.frame = // Calculate the content size here //
let snapshot = hosting.view.snapshot // output: an empty snapshot of the size
print(hosting.view.subviews.count) // output: 0
我尝试了layoutSubviews()、setNeedsLayout()、layoutIfNeeded()、loadView(),但仍然得到 0 个子视图。
2。 UIWindow.rootViewController (source here)
var vc = UIApplication.shared.windows[0].rootViewController
vc = vc.visibleController // loop through the view controller stack to find the top most view controller
let snapshot = vc.view.snapshot // output: a snapshot of the top most view controller
这几乎产生了我想要的输出。但是,我得到的快照实际上是一个屏幕截图,即带有导航栏、标签栏和固定大小(与屏幕大小相同)。我需要捕获的只是没有这些条的视图内容,有时可能比屏幕大(在这个例子中,我的视图是一个很长的列表)。
尝试查询vc.view.subviews 以查找我想要的表视图,但返回无用的[<_TtGC7SwiftUI16PlatformViewHostGVS_42PlatformViewControllerRepresentableAdaptorGVS_16BridgedSplitViewVVS_22_VariadicView_Children7ElementGVS_5GroupGVS_19_ConditionalContentS4_GVS_17_UnaryViewAdaptorVS_9EmptyView______: 0x7fb061cc4770; frame = (0 0; 414 842); anchorPoint = (0, 0); tintColor = UIExtendedSRGBColorSpace 0 0.478431 1 1; layer = <CALayer: 0x600002d8caa0>>]。
非常感谢任何帮助。
【问题讨论】:
-
你似乎专注于 50 张图片。您是指单个屏幕上的 50 张图像吗?这很可能是不可能的。这样看 -
Listis 等同于UITableView。什么样的设备一次显示50个cell/ -
@dfd 不是 50 张图片,而是 50 行。 50只是一个例子。让我这样说:我想创建一个包含所有这 50 行的 jpeg,以便可以将其保存到相机胶卷或通过电子邮件发送给其他人。
标签: ios xcode render swiftui snapshot