我在一个 ViewController 中有 2 个表视图。两个表视图的单元格高度不同。
在第一个表视图中,我通过委托方法进行计算heightForRowAt
因为在该表中单元格的内容是静态的。其次通过estimatedHeightForRowAt
委托方法,因为在该表格中单元格的内容是文本(可能很小或很大(。
所以问题是单元格高度第二个表视图固定为58。当显示大文本时,这种情况不会增加。
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView == tblHistory{
let h = ((tableView.frame.size.width - 16) * 7 / 5) + 74
return h
}
else{
return 58
}
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView == tblHistory{
let h = ((tableView.frame.size.width - 16) * 7 / 5) + 74
return h
}
else{
return 58
}
}
备注:我已经正确设置了所有约束,以根据文本调整单元格高度的大小。
问题是文本单元格的高度固定。当显示大文本时,这种情况不会增加。
您确实必须在情节提要的单元格内保持完美的约束。
真的有很多事情要知道。 您必须显示(屏幕截图(单元格的故事板,并显示链接UILabel
和其他项目的所有垂直约束。
一般来说,你不应该"固定"UILabel的高度,或者包括UILabel在内的整个"链"。 如果你做得正确,它的隐式高度将起作用。
如果约束设置正确,则无需计算高度。只需为两个表视图返回UITableViewAutomaticDimension
即可。
最好的解决方案是在heightForRowAt中使用相同的方法计算两个文本的高度:
func heightForText(string: String, width: CGFloat, font: UIFont) -> CGFloat {
let attrString = NSAttributedString(
string: string,
attributes: [NSFontAttributeName: font])
let size = attrString.boundingRect(
with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
return size.height
}