首页 > 解决方案 > UItableView 动态高度取决于内容

问题描述

如何使表格视图单元格高度动态化,单元格中有 1 个标签和 1 个图像,我的图像高度恒定为 70,标签高度取决于 api 文本,如果我的标签文本较大,则图像视图高度如此表视图单元格应适应标签高度,否则为图像视图。

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
}

下图只是选择图像的高度

标签: iosswiftuitableview

解决方案


通过执行以下操作获得基于其内容的 UITableViewCells 高度动态:

  1. 确保你的 UITableViewCell 的内容受到约束,这样动态内容被固定在单元格的顶部和底部。

一个人为的示例单元格:

class Cell: UITableViewCell {
    let label = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        // Allows your text to expand multiple lines
        label.numberOfLines = 0

        label.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(label)

        // Constrains a UILabel to the edges of the UITableViewCells content view
        label.topAnchor.constraint(equalTo: commentBox.topAnchor).isActive = true
        label.bottomAnchor.constraint(equalTo: commentBox.bottomAnchor).isActive = true
        label.leadingAnchor.constraint(equalTo: commentBox.leadingAnchor).isActive = true
        label.trailingAnchor.constraint(equalTo: commentBox.trailingAnchor).isActive = true
    }
}
  1. 如上所述,UITableViewAutomaticDimensionfunc tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

  2. 为了帮助您的 UITableView 计算动态高度,建议返回您认为您的单元格将达到的估计大小。 func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat


推荐阅读