ios - 以编程方式向已以编程方式添加到表格单元格的标签添加约束

标签 ios swift uitableview swift3 nslayoutconstraint

这是我尝试过的。

我已将我的行设置为根据其内容自动调整大小,如果我手动添加标签并手动向所述标签添加约束,这将非常有效。

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
}

当我运行项目时,我没有收到任何错误。这些行的大小似乎与标签的高度相匹配,并且标签正在响应以编程方式设置的约束,但该行似乎不知道该约束的存在。这是一个屏幕截图:

enter image description here

根据我过去的经验,这应该是我以编程方式向对象添加约束所需的全部内容。

我也尝试过使用:

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/

相关文章:

ios - 从 fetchedResultsController 获取不需要的节数

ios - 如何让 iPhone 上的返回键让键盘消失?

ios - Swift CGPoint x 和 y 覆盖编程约束

ios - 如何从 UITabBarController 以编程方式添加和打开 Nib 作为 subview Controller

ios - 自定义 uitableviewcell 中看似随机的标签文本更改

ios - 使用多个变量来创建字符串

ios - 创建 GIDGoogleUser 的模拟实例

ios - 使用 ObjectMapper 解析字典中的字典 Swift

ios - 如何将 uitableview 中的单个单元格链接到不同的 URL?

ios - UITableViewCell textLabel 在选择时改变位置