这是我的单元格布局的低质量模型:
静态单元格的初始高度(在情节提要中设置)为80。此单元格内有两个视图。底视图的固定高度为40。顶视图具有布局约束,以与顶边距对齐并与底视图垂直对齐。
在顶视图内是一个标签(蓝色)和一个按钮(黄色)
标签还具有与视图顶部对齐和与视图底部对齐的约束。这种布局和约束背后的想法是,例如,如果将单元格的高度增加到100,则底视图的高度将保持为40,而顶视图和标签的高度将被扩展为60。
我的标签具有换行符自动换行并且行数设置为0。我现在想要的是自动调整单元格的大小,以便在多于一行时显示标签的完整内容。我到底该怎么做?
我试过了:
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 80.0;
这是行不通的。像元的高度始终保持在80位,与线的数量无关UILabel
。
我也尝试过:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension;
}
结果与我的第一种方法相同。
我尝试的更复杂的方法如下:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let heightLabel = self.heightForView(text: self.lblTitle.text!, font: UIFont(name: "Helvetica Neue", size: 18)!, width: self.lblTime.width);
let heightView = (heightLabel + (80.0 / 2));
print("title label height \(heightLabel)");
print("title view height \(heightView)");
if (heightView > 80.0) {
return heightView;
}
return 80.0;
}
func heightForView(text: String, font: UIFont, width: CGFloat) -> CGFloat {
let label: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude));
label.numberOfLines = 0;
label.lineBreakMode = .byWordWrapping;
label.font = font;
label.text = text;
label.sizeToFit();
return label.frame.height;
}
输出:
title label height 42.5
title view height 82.5
但这似乎也不起作用,因为其他行(仅标签的第一行)没有显示。
我该如何工作?
编辑
我想当我知道标签的宽度时,用于计算标签高度的方法将起作用。但是我怎么知道呢?
根据个人经验,使UITableCells正确增长是iOS中最烦人的事情之一。最大的难题通常是约束。如果它们不完美,则细胞将不会生长。
关键是要能够从单元格内容视图的顶部到内容视图的底部绘制一条直线。因此从您的示例常量来看,常量应该类似于以下内容。
topView.top == contentView.top
label.top == topView.top
label.bottom == topView.bottom
topView.bottom == bottomView.top
bottomView.height == 40
bottomView.bottom == contentView.bottom
没有那条直线,布局就无法确定标签显示所有内容的正确高度。
因此,您可以在一个新的示例项目中找到一个相当简单的版本:
class ViewController: UITableViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 80.0
label.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
}
使用相同的布局:表单元格的布局
结果显示在模拟器中。结果图像
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句