【问题标题】: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
【问题讨论】:
-
欢迎来到 Stack Overflow。请使用tour 并查看How to Ask。您的第一步应该是搜索...前往谷歌(或您最喜欢的搜索引擎)并搜索swift uitableviewcell dynamic height。您会发现很多很多的答案/文章/文档/博客/教程/等链接。
-
标签:
ios
swift
uitableview
【解决方案1】:
通过执行以下操作获得基于其内容的 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
}
}
-
如上所述,从func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat返回UITableViewAutomaticDimension
-
为了帮助您的 UITableView 计算动态高度,建议返回您认为您的单元格将达到的估计大小。
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat