【问题标题】:UItableView dynamic height depending on contentUItableView 动态高度取决于内容
【发布时间】:2021-12-12 03:30:45
【问题描述】:

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

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

below image just picking height of image

【问题讨论】:

标签: ios swift uitableview


【解决方案1】:

通过执行以下操作获得基于其内容的 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. 如上所述,从func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat返回UITableViewAutomaticDimension

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 2017-01-17
    • 2018-09-07
    • 1970-01-01
    相关资源
    最近更新 更多