可变长度的文本数据被注入(inject)到 tableview 单元格标签中。为了使每个单元格的高度大小合适,我在 viewDidLoad()
中实现了:
self.tableView.estimatedRowHeight = 88.0
self.tableView.rowHeight = UITableViewAutomaticDimension
这估计高度为 88.0 像素,如果更大,应该自动调整高度。它非常适合尚未滚动到的单元格(因为在滚动到单元格时调用UITableViewAutomaticDimention
),但不适用于单元格在用数据加载表格时最初呈现在屏幕上。
我已经尝试重新加载数据(如许多其他资源中所建议的那样):
self.tableView.reloadData()
在 viewDidAppear()
和 viewWillAppear()
中都没有帮助。我迷路了..有谁知道如何渲染最初在屏幕上加载的单元格的动态高度?
最佳答案
试试这个:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
编辑
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
swift 4
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
swift 4.2
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
定义以上两种方法。
它解决了这个问题。
PS:此功能需要顶部和底部约束。
关于ios - UITableView 单元格的动态高度问题(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30494702/