title: Programmatically add constraints to labels that have been programmatically added to a table cell
body: <p>Here's what I've tried.</p>
  
  <p>I've set my rows to automatically resize based on their content which works perfectly if I manually add labels and manually add constraints to said labels.</p>
  
  <pre><code>override func viewDidLoad() {
      tableView.rowHeight = UITableViewAutomaticDimension
      tableView.estimatedRowHeight = 100
  }
  </code></pre>
  
  <p>Then I'm adding labels and their constraints like so:</p>
  
  <pre><code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; 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
  }
  </code></pre>
  
  <p>When I run the project, I don't get any errors. The rows seem to be sizing to the height of the label and the label is responding to the programmatically set constraint but the row doesn't seem to know that the constraint exists. Here's a screenshot:</p>
  
  <p><a href="https://i.stack.imgur.com/6tB0H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6tB0H.png" alt="enter image description here"></a></p>
  
  <p>In my past experience, this should have been all that I needed to add constraints to objects programmatically.</p>
  
  <p>I've also tried using:</p>
  
  <pre><code>tableView.beginUpdates()
  tableView.endUpdates()
  </code></pre>
  
  <p>But that doesn't help. When the table reloads, it reloads right back to the same position.</p>