首页 > 解决方案 > 如何在tableview swift中自动调整标题视图的大小?

问题描述

我刚刚在我的表格视图中放置了一个视图,该视图包含图像和标签。但是标签内容是动态的,不想裁剪它,而是我想根据需要增加视图的高度。但标题视图也不接受约束。那我能实现吗?问题出现在查找朋友按钮上方的标签上。 在此处输入图像描述

标签: iosswiftxcodeuitableview

解决方案


您需要使用文本估计标签高度并加上图像/按钮高度来计算标题视图的总高度

func estimatedLabelHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat {

    let size = CGSize(width: width, height: 1000)

    let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)

    let attributes = [NSAttributedStringKey.font: font]

    let rectangleHeight = String(text).boundingRect(with: size, options: options, attributes: attributes, context: nil).height

    return rectangleHeight
}

这是估计标题高度的方法:

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return label size + other size
}

或者您可以使用自动布局来避免估计高度:

  • 设置标签 numberOfLines = 0
  • 在垂直方向的每个单元格之间设置垂直填充约束
  • 返回UITableView.automaticDimension
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
   return UITableView.automaticDimension
}

推荐阅读