title: Need assistance regarding creating auto layout constraints programmatically
body: <p>This is the first time I am trying to create <code>auto layouts  constraints</code> programmatically and here is my code</p>
  
  <pre><code>- (void)viewDidLoad {
      [super viewDidLoad];
  
      UIView *view1 = [[UIView alloc]init];
      view1.backgroundColor = [UIColor lightGrayColor];
      [self.view addSubview:view1];
      [view1 setTranslatesAutoresizingMaskIntoConstraints:NO];
  
      NSDictionary *views = NSDictionaryOfVariableBindings(view1);
  
      NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|-[view1]-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:views];
  
      NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[view1]-|" options:0 metrics:nil views:views];
  
      [view1 addConstraints:constraints];
  
      [view1 addConstraints:verticalConstraints];
  }
  </code></pre>
  
  <p>This is what I amy trying to do in code.</p>
  
  <p><a href="https://i.stack.imgur.com/1gzDj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1gzDj.png" alt="enter image description here"></a></p>
  
  <p>And this huge error I am getting</p>
  
  <blockquote>
    <p>2015-12-16 12:13:59.254 test5b[1138:430691] The view hierarchy is not
    prepared for the constraint:    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(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug. 2015-12-16 12:13:59.259 test5b[1138:430691] View hierarchy unprepared for
    constraint.   Constraint: 
      Container hierarchy:  >     View not found in container hierarchy: >     That view's superview: ; layer = > 2015-12-16 12:13:59.260 test5b[1138:430691] <strong>*
    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:
    view:>'
    *</strong> First throw call stack: (0x1829f4f5c 0x1975e7f80 0x1829f4ea4 0x183890ef4 0x18804c620 0x18804c428 0x18804c2d0 0x18804c194
    0x188056504 0x183890aa0 0x18805330c 0x188056420 0x1000d65f0
    0x187f63a0c 0x187fd2fcc 0x187fd2f68 0x1881f494c 0x188200de4
    0x1829ac48c 0x1829abdc4 0x1829a9d28 0x1828d8dc0 0x18da2c088
    0x187fb2f60 0x1000d6ab8 0x197e128b8) libc++abi.dylib: terminating with
    uncaught exception of type NSException (lldb)</p>
  </blockquote>