title: Programmatically Add CenterX/CenterY Constraints
body: <p>I have a UITableViewController that doesn't display any sections if there is nothing to show. I've added a label to indicate to the user that there is nothing to display with this code: </p>
  
  <pre><code>label = UILabel(frame: CGRectMake(20, 20, 250, 100))
  label.text = "Nothing to show"
  self.tableView.addSubview(label)
  </code></pre>
  
  <p>But now, I want it to be centered Horizontally and Vertically. Normally, I would choose the two options highlighted (plus ones for height and width) in the screenshot: </p>
  
  <p><img src="https://i.stack.imgur.com/I953j.png" alt="enter image description here"></p>
  
  <p>I've tried the following code to add the constraints but the app crashes with error: </p>
  
  <pre><code>label = UILabel(frame: CGRectMake(20, 20, 250, 100))
  label.text = "Nothing to show"
  
  let xConstraint = NSLayoutConstraint(item: label, attribute: .CenterX, relatedBy: .Equal, toItem: self.tableView, attribute: .CenterX, multiplier: 1, constant: 0)
  let yConstraint = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: self.tableView, attribute: .CenterY, multiplier: 1, constant: 0)
  
  label.addConstraint(xConstraint)
  label.addConstraint(yConstraint)
  </code></pre>
  
  <p>error: </p>
  
  <pre><code>When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug.
  2014-12-23 08:17:36.755 [982:227877] *** Assertion failure in -[UILabel _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:], /SourceCache/UIKit/UIKit-3318.16.21/NSLayoutConstraint_UIKitAdditions.m:560
  </code></pre>
  
  <p>The label should always center horizontally and vertically because the app supports rotation of the device. </p>
  
  <p>What am I doing wrong? How do I add these constraints successfully?</p>
  
  <p>Thanks!</p>