ios - UItableView 动态高度取决于内容
问题描述
如何使表格视图单元格高度动态化,单元格中有 1 个标签和 1 个图像,我的图像高度恒定为 70,标签高度取决于 api 文本,如果我的标签文本较大,则图像视图高度如此表视图单元格应适应标签高度,否则为图像视图。
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
解决方案
通过执行以下操作获得基于其内容的 UITableViewCells 高度动态:
- 确保你的 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
}
}
如上所述,
UITableViewAutomaticDimension
从func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
为了帮助您的 UITableView 计算动态高度,建议返回您认为您的单元格将达到的估计大小。
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat
推荐阅读
- java - IntelliJ IDEA 检查警告参数可能为空
- python - 使用 NLP 工具对句子进行联合分割
- r - 将 RStudio ggplot 图插入 RShiny 仪表板
- jquery - 按钮的控制流 - 打开和关闭设置
- javascript - 如何将这些臃肿的条件语句重构为数组
- php - 在for循环php中设置数组值
- django - 无法从 django 模板中的表单中获取数据?
- android - 如何在android中使用TextInputLayout
- javascript - JS Class:在类中创建变量而不被构造函数调用的最聪明的方法
- python - Python SQLAlchemy在给定时间戳之前获取最后一个条目(按时间戳)