ios - 如何在tableview swift中自动调整标题视图的大小?
问题描述
我刚刚在我的表格视图中放置了一个视图,该视图包含图像和标签。但是标签内容是动态的,不想裁剪它,而是我想根据需要增加视图的高度。但标题视图也不接受约束。那我能实现吗?问题出现在查找朋友按钮上方的标签上。
解决方案
您需要使用文本估计标签高度并加上图像/按钮高度来计算标题视图的总高度
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
}
推荐阅读
- c - 消息队列 - 服务器只响应一种类型的消息
- c# - 服务器端数据表搜索为字符串项返回 NULL
- python - 微调 HuggingFace NLI 模型(RoBERTa/BART)时,损失为“nan”
- c# - 使用 c# 库恢复 azure blob 快照
- python - 类型错误:step() 缺少 1 个必需的位置参数:'y'
- linux - 在Shell脚本中将文件中的字母更改为大写
- javascript - 如何使用字符串与对象文字属性定义类型?
- concurrency - 如何理解两个线程递增和打印一个全局变量的结果?
- r - 在库中找不到 rJava“EXTPR_PTR”过程入口点
- php - composer dump-autoload -o 跳过我所有的课程