首页 > 解决方案 > 具有不同 UITableViewCells 和动态内容的 UITableView

问题描述

在我们的应用程序中,我们经常使用具有类型的显示项目列表作为数据源,在可滚动列表中UITableViews显示不同的自定义。UITableViewCells然后在TableView'scellforRowAt函数中,我们UITableViewCell根据显示项目的类型决定使用哪个自定义。

这种方法现在会导致UITableViewCell从 Internet 加载和显示图像的问题,因为视图还不知道图像的大小。

这是我正在尝试构建的自定义视图:请参阅自定义 UITableViewCell

但是,我尝试仅从自定义视图中的图像开始。由于该TableView行不知道图像将有多大,因此视图出现时不会显示图像。只有在向下和向上滚动到图像应该在的位置之后,单元格才会按照我想要的方式调整大小。我将图像的顶部、前导和尾部约束设置为 0,以便图像完全填充单元格。

加载图像并在此类单元格中显示它们的最佳做法是什么?根据实际图像大小调整单元格的大小?

viewDidLoad我设置

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 80

cellForRowAtIndexPath

let cell: CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
cell.imageView.contentMode = .scaleAspectFit
tableView.beginUpdates()
cell.imageView.kf.setImage(with: URL(string: item.getImageUrl()), placeholder: nil, options: nil, progressBlock: nil) { (image, error, cacheType, url) in
    tableView.endUpdates()
}
cell.isUserInteractionEnalbed = false
cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: .greatestFiniteMagnitude)
cell.accessoryType = .none

return cell

标签: iosswiftuitableview

解决方案


当您配置表格视图或加载视图时:编写以下内容:

yourTableView.estimatedRowHeight = 70.0 // this can be any height you want to set when table loads first time.
yourTableView.rowHeight = UITableViewAutomaticDimension

或者,如果您从那里进行配置,您可以从 storyboard/xib 设置这些设置。在此处输入图像描述请参阅此处的 uitableview 设置。


推荐阅读