【发布时间】:2017-08-07 09:46:44
【问题描述】:
是否可以在设置文本后调整UITabeView Header 的大小?
在我的 xib 中,我得到了一个 TableView,其标题为 1 行文本的高度为 42。对于 2 行,我需要 52 的高度,对于 3,我需要 62。标题动态设置为标题。但是 heightForHeaderInSection 函数在生命周期设置标题文本之前被调用。所以可能没有显示第 2 行和第 3 行。
我写了一个方法告诉我标题有多少行文本但是如何更新标题?如果我打电话给tableView.reloadData(),我最终会陷入无限循环。如果我为每个 lineamoun 设置 var
t 我发现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}
}
【问题讨论】:
-
为
linesOfHeader设置一个属性观察器,并从linesOfHeader的disSet方法内部调用tableView.reloadData()。这样,每次linesOfHeader更改时,您的tableView只会重绘一次。 -
字符串的boundedrect方法可以帮助您获取标签的高度和宽度,您可以从中将高度传递给标题。
-
@DávidPásztor 相同的循环。 reloadData() 调用 viewForHeaderInSection 我设置页眉的行。所以我最终会陷入一个循环。
-
所以不要在
viewForHeaderInsection中设置linesOfHeader,而是在行数实际可以改变的时候设置。 -
此时。当我设置文本时,行会发生变化。所以我必须把它放在那里。
标签: ios swift uitableview swift3 header