我正在尝试以编程方式创建一个自动调整大小的表格 View ,但单元格没有增加它们的高度以适应内容,因此下一个单元格从前一个单元格开始。请问我还需要做什么吗?
MyTableViewControler.swift
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 120
tableView.rowHeight = UITableViewAutomaticDimension
tableView.translatesAutoresizingMaskIntoConstraints = false
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier)
if (cell == nil) {
cell = UITableViewCell.init(style: .default, reuseIdentifier: reuseIdentifier)
cell?.translatesAutoresizingMaskIntoConstraints = false
let contentView = (cell?.contentView)!
// Title
let titleL = UILabel(frame: .zero)
contentView.addSubview(titleL)
titleL.translatesAutoresizingMaskIntoConstraints = false
titleL.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
titleL.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: 0).isActive = true
titleL.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 0).isActive = true
}
return cell
}
最佳答案
你还应该添加底部约束
titleL.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0).isActive = true
关于swift - 以编程方式创建自动调整大小的 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50641368/