我试图将SwiftUI视图渲染为UIImage,然后让用户选择保存到相机胶卷还是通过电子邮件发送给其他人。
例如,我想将50行列表渲染成UIImage。
例如,我想将50行列表渲染成UIImage。
struct MyList: View {
var body: some View {
List {
ForEach(0 ..< 50, id:\.self) {
Text("row \($0)")
}
}
}
}
过去几周在网络上搜索了很久,但仍然没有找到。 我尝试了两种不同的方法。
1. UIHostingController (这里是来源)
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()
,但仍然没有子视图。
2. UIWindow.rootViewController (源代码在这里)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>>]
。
非常感谢任何帮助。
List
等同于一个UITableView
。什么样的设备可以同时显示50个单元格? - user7014451