【问题标题】:Height of a dynamic cell - SWIFT动态单元格的高度 - SWIFT
【发布时间】:2020-12-06 21:23:09
【问题描述】:

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

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

在 viewController 我有tableView.rowHeight = UITableView.automaticDimension。

谁能帮忙。谢谢

【问题讨论】:

标签: swift uitableview dynamic height cell


【解决方案1】:

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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-03
    • 2015-08-10
    • 2014-06-23
    • 2020-02-02
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    相关资源
    最近更新 更多