【问题标题】:Change the height of parent UITableView cell based on the height of child TableViewControllers根据子 TableViewControllers 的高度改变父 UITableView 单元格的高度
【发布时间】:2020-11-14 16:29:08
【问题描述】:
WidgetsVC(has a table view and uses tableview automatic dimension)
->ListVC(uses tableview automatic dimension and embedded as a row inside WidgetVC)
->TableViewCell-Image(embedded inside ListVC)
图片是从网络上下载的,每张图片都有自己的高度。那么当图片加载完毕后,如何改变 WidgetVC 中的行高呢?
WidgetsVC 可以包含多个 ListVC
提前致谢。
【问题讨论】:
标签:
swift
uitableview
uiviewcontroller
【解决方案1】:
由于您将UIViewControllers 嵌入到UITableViewCell 中,因此您不能依靠自动布局根据加载的图像自动更改高度。
因此,我建议您将图像加载逻辑移至WidgetsVC,并在每次加载图像时执行以下操作。
- 计算加载图像的高/宽纵横比(如果您的图像加载库有完成处理程序,您可以将其用于计算目的)。
- 计算图像的拟合高度(这仍然在
WidgetVC 中的图像加载器的完成处理程序中)。
let imageHeight = aspectRatio * self.tableView.frame.width
- 将图像及其计算的拟合高度存储在数据结构中。
- 在步骤 1 中引入的完成处理程序结束时调用
tableView.reloadData()。
- 在您的
tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) 方法中,传入存储在数据结构中的高度。
- 在您的
tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 方法中,传入存储在数据结构中的图像。
您可以在上述步骤 3 中使用的数据结构示例如下所示。
struct WidgetListImageModel{
var height: CGFloat
var image: UIImage
}
var widgetImageModels: [Int: WidgetListImageModel] = [:]
请注意,widgetImageModels 是 Dictionary,原因如下。
- 您可能已经有一个通过
WidgetVC 的cellForRowAt 方法传递的数据模型,因此您可以独立存储所需的信息,而不是对其进行修改。
- 您可以在
heightForRowAt 和cellForRowAt 方法中使用indexPath.row 作为索引,轻松查询widgetImageModels 以获取所需信息。
- 您不必在
WidgetListImageModel 中维护要为其加载数据的单元格的索引。
由于您没有提供任何代码,因此上述步骤假设了您当前实施的许多事情。如果您有任何问题或答案不适用于您的代码,请告诉我。我会尽力帮助你的。
干杯!