这是我尝试过的。
我已经将我的行设置为根据它们的内容自动调整大小,如果我手动添加标签并手动向所述标签添加约束,这将完美地工作。
override func viewDidLoad() {
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
}
然后我添加标签及其约束,如下所示:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TypeCell", for: indexPath) as UITableViewCell
// Programmatically add a label
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = dataLabels[indexPath.row] // dataLabels is an array of my labels
label.tag = indexPath.row
cell.contentView.addSubview(label)
// Programmatically add constraints
label.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 15).isActive = true
label.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: 15).isActive = true
return cell
}
当我运行项目时,我没有收到任何错误。行的大小似乎与标签的高度一致,并且标签正在响应以编程方式设置的约束,但该行似乎不知道约束存在。这是一个屏幕截图:
根据我过去的经验,这应该是我以编程方式向对象添加约束所需的全部内容。
我也试过使用:
tableView.beginUpdates()
tableView.endUpdates()
但这无济于事。当桌子重新加载时,它会重新加载到相同的位置。
看起来像一个常见的“哎呀”错误......
// Programmatically add constraints
label.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 15).isActive = true
label.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: 15).isActive = true
这两行说的是:
然后
您真正想要的是ContentView的底部等于标签的底部加上 15pts。
因此,您可以将该行更改为:
// set Bottom of Label to Bottom of View MINUS 15pts
label.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -15).isActive = true
要么
// set Bottom of View to Bottom of Label PLUS 15pts
cell.contentView.bottomAnchor.constraint(equalTo: label.bottomAnchor, constant: 15).isActive = true
那应该这样做。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句