我正在尝试创建一个表格 View 单元格以容纳不同长度的文本,并且我需要每个单元格都具有动态高度。我试过使用以下但没有显示:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 410
有人可以帮我吗?
最佳答案
要为行高和估计行高设置自动尺寸,请确保按照以下步骤使自动尺寸对单元格/行高布局有效。我刚刚测试了以下步骤和代码并且工作正常。
- 分配和实现 TableView 数据源和委托(delegate)
- 将
UITableViewAutomaticDimension
分配给 rowHeight 和 estimatedRowHeight - 实现委托(delegate)/数据源方法(即
heightForRowAt
并向其返回值UITableViewAutomaticDimension
)
-
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Don't forget to set dataSource and delegate for table
table.dataSource = self
table.delegate = self
// Set automatic dimensions for row height
table.rowHeight = UITableViewAutomaticDimension
table.estimatedRowHeight = UITableViewAutomaticDimension
}
// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
对于 UITableviewCell 中的标签实例
- 设置行数=0(&换行模式=截尾)
- 设置关于其父 View /单元格容器的所有约束(顶部、底部、左右)。
- 可选:设置标签的最小高度,如果您希望标签覆盖的最小垂直区域,即使没有数据也是如此。
注意:如果您有多个具有动态长度的标签(UIElements),应根据其内容大小进行调整:为您选择的标签调整“Content Hugging and Compression Resistance Priority”想要以更高的优先级展开/压缩。
关于ios - 创建具有动态高度的 UITableView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48585335/