title: Adding View Programatically With Auto Layout Gives 'NSGenericException', reason: 'Unable to install constraint on view
body: <p>I am adding a view as a subview using <code>[self.view addSubview:myView]</code>. This works fine in portrait mode. However, it doesn't work at all in landscape. How do I add layout constraints programatically?</p>
  
  <p>My view currently looks like portrait rectangle and I need it to look like landscape rectangle in landscape mode. </p>
  
  <p>I tried this code to see how constraints in code work but it always results in an exception. The code is: </p>
  
  <pre><code>[self.view addSubview:_preView];
  NSLayoutConstraint *myConstraint = [NSLayoutConstraint
   constraintWithItem:_preView
   attribute:NSLayoutAttributeBottom
   relatedBy:NSLayoutRelationEqual
   toItem:self.view.superview
   attribute:NSLayoutAttributeBottom
   multiplier:1.0
   constant:-239];
  [_preView addConstraint:myConstraint];
  </code></pre>
  
  <p>This always results in an exception. I know the above code just attempts to ensure that the bottom of preview is 239px above the bottom of main view. But that doesn't work either.</p>
  
  <p>Could you help me out with sorting this so that I can resolve the landscape issue?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>The exception generated is:</p>
  
  <p><code>2013-08-05 16:13:28.889 Sample Code[33553:c07] *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to install constraint on view.  Does the constraint reference something from outside the subtree of the view?  That's illegal. constraint:&lt;NSLayoutConstraint:0x912c430 UIView:0x8561340.bottom == UILayoutContainerView:0x8257340.bottom - 20&gt; view:&lt;UIView: 0x85774e0; frame = (0 0; 320 568); opaque = NO; autoresize = W+H; autoresizesSubviews = NO; layer = &lt;CALayer: 0x8577490&gt;&gt;'
  *** First throw call stack:
  (0x1a04012 0x173be7e 0x1a03deb 0x12ee4a0 0xbb983e 0xbb9a27 0xbb9b76 0xbb9d3b 0xbb9c4d 0x1c0d9 0x11395b3 0x19c3376 0x19c2e06 0x19aaa82 0x19a9f44 0x19a9e1b 0x24027e3 0x2402668 0x67fffc 0x2d3d 0x2c65)
  libc++abi.dylib: terminate called throwing an exception
  (lldb)</code></p>
  
  <p>I have added the subview before adding in the constraint so I am pretty sure the view is in hierarchy.</p>
  
  <p><strong>UPDATE 2</strong></p>
  
  <p>I set the parent view's property to `Autoresize Subviews' in IB. The subview now converts into landscape rectangle when the device is turned but its too narrow. I now need the code to make sure its of correct width maybe?</p>