【发布时间】:2017-03-16 13:03:45
【问题描述】:
这是我尝试过的。
我已将行设置为根据其内容自动调整大小,如果我手动添加标签并手动向所述标签添加约束,则效果很好。
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()
但这无济于事。当表格重新加载时,它会立即重新加载回相同的位置。
【问题讨论】:
-
let topConstraint = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: cell.view, attribute: .topMargin, multiplier: 1.0, constant: 16) let bottomConstraint = NSLayoutConstraint (item: label, attribute: .bottom, relatedBy: .equal, toItem: cell.view, attribute: .bottomMargin, multiplier: 1.0, constant: 16) NSLayoutConstraint.activate([topConstraint, bottomConstraint]) 试试这个
-
cell有 4 个subviews(contentView、2 个分隔视图和UILabel),因此简单地调用view不会访问任何特定内容。尽管如此,我尝试了它,但我收到一条错误消息:UITableViewCellhas no memberview -
抱歉是 contentView
标签: ios swift uitableview swift3 nslayoutconstraint