title: iOS adding constraints programmatically in Swift
body: <p>So, I'm done using the <code>IB</code> in <code>Xcode</code> and want to write all <code>UI</code> in Swift.</p>
  
  <p>So what I've done is:</p>
  
  <ul>
  <li>Created a new <code>UIView</code> to contain the elements i want to write - lets call it "TestView"</li>
  <li>I've added <code>TestView</code> to a <code>VC</code> as a sub view.</li>
  <li><p>In the <code>TestView</code> class I've added the elements like this:</p>
  
  <pre><code>class TestView: UIView {
        var someLabel:UILabel!
        override init(frame: CGRect) {
              super.init(frame: frame)
  
              self.someLabel = UILabel(frame: CGRect(x: self.frame.midX, y: oneSixthHeight, width: 100, height: 22))
              self.someLabel.text = "test"
  
              var constraints:[NSLayoutConstraint] = []
              self.someLabel.translatesAutoresizingMaskIntoConstraints = false
              let rightsideAnchor:NSLayoutConstraint = NSLayoutConstraint(item: self.someLabel, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 1)
  
               constraints.append(rightsideAnchor)
               NSLayoutConstraint.activateConstraints(constraints)
        }
  }
  </code></pre></li>
  </ul>
  
  <p>With this I expect the <code>UILabel</code> to be anchored to the right side of the view.</p>
  
  <p>However, I do get this error:</p>
  
  <blockquote>
    <p>Terminating app due to uncaught exception 'NSGenericException', 
        reason: 'Unable to activate constraint with items > and > because they have no common ancestor.<br>
        Does the constraint reference items in different view hierarchies?  That's illegal.'</p>
  </blockquote>
  
  <p>What am I doing wrong?</p>