也有类似的问题,但没有答案适合我。在动态表格中,我想显示不同高度的图像。每个单元格都有一个UIImageView
和contentMode = .scaleAspectFit
,所以图像很好地占据了表格的宽度并根据需要获取高度。带图像的动态UITableView
表视图控制器:
class TableTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ImageTableViewCell.self), for: indexPath) as! ImageTableViewCell
let image = indexPath.row == 0 ? UIImage(named: "1.jpg")! : UIImage(named: "2.jpg")!
cell.customImageView.image = image
return cell
}
}
结果:
正如可以看到的是,电池的高度是不正确的(图像视图顶部和底部的图像视图的红色背景)。我相信这是因为图像视图的intrinsicContentSize
等于图像大小,这就是为什么单元格的高度计算不正确(不考虑内容模式)。我试图计算图像的高度和增加高度约束的图像视图:
cell.heightConstraint.constant = cell.frame.width * image.size.height/image.size.width
,但它打破了细胞的内容视图的约束。
该项目可以下载here>>
所以基本上你想要的tableview具有动态高度单元? –
正确设置约束条件 – Harish
@Dharmesh Kheni是的,所以单元格的高度等于图像高度。 – sash