我的UITableView
的标题包含一个文字包装的标签,可以有可变的文本,从0到4行。
由于这个原因,我不能使用这个函数预先确定header的高度:
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
是否有可能以某种方式让标题自行调整大小?
自动调整大小
如果你使用的是自动布局,你可以为UITableView
创建自动调整单元格/页眉/页脚的大小,像这样:
tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableViewAutomaticDimension
<<p> 头/strong> 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
}
请注意,计算出的高度仅为字符串的,您可能需要添加一些填充。