是否可以在文本设置为UITabeView
标题后调整其大小? 在我的 xib 中,我得到了一个 TableView,其标题高度为 42,用于 1 行文本。对于 2 行,我需要 52 的高度,对于 3 行,我需要 62 的高度。 标题动态设置为标题。但是,在生命周期设置标头文本之前调用heightForHeaderInSection
func。所以也许没有显示第 2 行和第 3 行。
我写了一个方法,告诉我标题有多少行文本,但如何更新标题? 如果我打电话tableView.reloadData()
我最终会陷入无限循环。如果我为每行设置 var 我发现heightForheaderInSection
从未被调用。
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: headerCell) as! SectionHeader
cell.titleLabel.text = self.sectionTitle
linesOfHeader = cell.getNumberOfLines()
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if(linesOfHeader == 1) { return 44}
else if(linesOfHeader == 2) {return 52}
else { return 62}
}
支持动态标头高度的更好解决方案是使用"UITableViewAutomaticDimension",如下所示:
在视图中,添加以下行:
self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension
self.tableView.estimatedSectionHeaderHeight = 50
并删除函数高度为标题InSection
然后允许标签扩展到所需的行数
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: headerCell) as! SectionHeader
cell.titleLabel.text = self.sectionTitle
cell.titleLabel.numberOfLines = 3
return cell
}
如果标题高度与单元格高度重叠,则将这两行添加到 viewDidLoad
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 40 // estimated cell height