我正在尝试创建具有动态大小(特别是高度)的表格单元格。单元格包含 4 行文本和 ImageView 。 ImageView 中的图像通常具有较大的分辨率,因此应该对其进行缩放以适合 ImageView 。我使用 aspectFit 模式在 ImageView 内进行缩放。
如果我硬编码单元格高度, ImageView 会收到额外的空间(用颜色突出显示)
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 500
}
要删除额外的填充,我需要在缩放后计算图像尺寸。 我如何在 Swift 中做到这一点?
我也试过 UITableViewAutomaticDimension,但是单元尺寸变得很大(取决于图像分辨率),因为单元尺寸是根据全分辨率图像计算的,而不是按比例计算的(使用 aspectFit 模式)
this answer 中提供了另一种解决方案, 但此解决方案的性能非常差,对于 TableView 来说是 Not Acceptable 。我相信有更好的解决方案,因为图像已经被系统缩放以适应宽度,我只需要知道缩放图像的尺寸。
最佳答案
发布问题后,我想到了新的想法。如果缩放模式始终是 aspectFit 并且单元格宽度始终相同,那么知道我可以计算缩放因子。之后可以计算单元格高度:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
// current cell height = 4 text lines + scaled image
// Number of text lines
let numberOfTextLines: CGFloat = 4.0
// Line height of font used in text labels
let textLineHeight = UIFont.systemFont(ofSize: 17).lineHeight
// Size of image to show in cell
let imageSize = imageRecords[indexPath.row].image!.size
// Scale factor: cell width to image width
let scale = self.tableView.bounds.width / imageSize.width
// Cell height = sum of all lines height + scaled image height
return (numberOfTextLines * textLineHeight) + (scale * imageSize.height)
}
要提高单元格高度精度,应考虑单元格边距。
关于ios - 缩放后如何计算图像尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41693824/