0

my 中的标题UITableView包含一个自动换行的标签,该标签可以包含可变文本,范围从 0 到 4 行。

出于这个原因,我不能用这个函数真正确定标题高度:

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

是否有可能让标题自行调整大小?

4

1 回答 1

3

自动调整大小

如果您使用自动布局,您可以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
    }

请注意,计算出的高度适用于字符串,您可能需要添加一些填充。

于 2015-10-04T02:20:29.080 回答