如何在 tableview swift 中制作自动调整大小 header 视图?

How to make auto resizing header view in tableview swift?

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

您需要用文本估算标签高度,并用图片/按钮高度估算 header 视图的总高度

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
}

这里是估算header身高的方法:

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

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

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

TableView header 高度不会自动刷新,每次内容变化需要自己重新计算高度。高度重新计算和 tableview header 刷新可以在 'viewDidLayoutSubviews' 方法中完成。

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        guard let headerView = tableView.tableHeaderView else {
            return
        }
        let size = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)

        if headerView.frame.size.height != size.height {
            headerView.frame.size.height = size.height
            tableView.tableHeaderView = headerView
            // This only seems to be necessary on iOS 9.
            tableView.layoutIfNeeded()
        }
    }

答案和代码片段是“Variable Height Table View Header”post 的简要摘要,可在 usyourloaf

访问