这是我尝试过的。
我已将我的行设置为根据其内容自动调整大小,如果我手动添加标签并手动向所述标签添加约束,这将非常有效。
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。
然后
- 使 Label 的底部等于 ContentView 的底部加上 15pts。
您真正想要的是 ContentView 的底部等于 Label 的底部加上 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
应该这样做。
关于ios - 以编程方式向已以编程方式添加到表格单元格的标签添加约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42834908/