动态单元格的高度-SWIFT

问题描述

如何从自定义单元格视图中获取动态单元格的高度。

我尝试过 let height = contentView.layer.frame.heightlet height = contentView.frame.height 但是所有单元格都返回44,尽管它们的高度不同。

在viewController上,我有tableView.rowHeight = UITableView.automaticDimension

任何人都可以帮忙。谢谢

解决方法

Swift 5版本。这应该起作用。

func cellHeight(for indexPath: IndexPath) -> CGFloat {
    let cell = self.tableView.cellForRow(at: indexPath)
    return cell?.contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height ?? 0
}

您可以在tableView.reloadData()之后调用此函数。例如:

tableView.reloadData()
let indexPath = IndexPath(row: 0,section: 0) 
let height = cellHeight(for: indexPath)
print(height)

Important:您需要将单元格正确配置为动态高度。

您不必调用tableView.rowHeight = UITableView.automaticDimension,因为它是默认值。 更重要的是,您需要正确设置tableView.estimatedRowHeight