my 中的标题UITableView
包含一个自动换行的标签,该标签可以包含可变文本,范围从 0 到 4 行。
出于这个原因,我不能用这个函数真正确定标题高度:
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
是否有可能让标题自行调整大小?
my 中的标题UITableView
包含一个自动换行的标签,该标签可以包含可变文本,范围从 0 到 4 行。
出于这个原因,我不能用这个函数真正确定标题高度:
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
是否有可能让标题自行调整大小?
如果您使用自动布局,您可以UITableView
像这样创建自动调整单元格/页眉/页脚:
细胞
tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableViewAutomaticDimension
标头
tableView.estimatedSectionHeaderHeight = 68.0
tableView.sectionHeaderHeight = UITableViewAutomaticDimension
页脚
tableView.estimatedSectionFooterHeight = 68.0
tableView.sectionFooterHeight = UITableViewAutomaticDimension
如果您想动态计算估计高度,也可以使用该UITableViewDelegate
方法。estimatedHeightForHeaderInSection
例如:
func tableView(tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
let calculatedHeight = estimatedHeaderHeightCalculator(section: section)
return calculatedHeight
}
我通常会跳过自动调整大小并手动计算单元格的大小。动态地自动调整单元大小是很挑剔的,花我一天的时间来改变拥抱/压缩约束是我对地狱的想法。
如果您知道有问题的字符串,请按如下方式计算大小:
extension: String {
func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: CGFloat.max)
let boundingBox = self.boundingRectWithSize(constraintRect, options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: [NSFontAttributeName: font], context: nil)
return boundingBox.height
}
}
然后在你的UITableViewDelegateMethod
:
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let constrainingWidth = tableView.bounds.width
let font = UIFont(name: "YourHeaderLabelFont", size: 16)!
let headerString = yourHeaderString
let heightForString = headerString.heightWithConstrainedWidth(constrainingWidth, font: font)
return heightForString
}
请注意,计算出的高度仅适用于字符串,您可能需要添加一些填充。