Autolayout Crash while setting view position to superview

Sanoj picture Sanoj · Oct 6, 2014 · Viewed 7.1k times · Source

I am getting crash when I am setting the view position

2014-10-06 15:25:01.896 sample[21174:60b] 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 _viewHierarchyUnpreparedForConstraint:] to debug.

2014-10-06 15:25:01.898 sample[21174:60b] 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 _viewHierarchyUnpreparedForConstraint:] to debug.

Here is code..

    self.redView = [UIView new];
self.redView.translatesAutoresizingMaskIntoConstraints = NO;
self.redView.backgroundColor = [UIColor colorWithRed:0.95 green:0.47 blue:0.48 alpha:1.0];

self.yellowView = [UIView new];
self.yellowView.translatesAutoresizingMaskIntoConstraints = NO;
self.yellowView.backgroundColor = [UIColor colorWithRed:1.00 green:0.83 blue:0.58 alpha:1.0];

[self.view addSubview:self.redView];
[self.view addSubview:self.yellowView];

    NSDictionary *viewDictionary = @{@"redView": self.redView};

NSArray *constraints_H = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[redView(100)]" options:0 metrics:nil views:viewDictionary];
NSArray *constraints_V = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[redView(100)]" options:0 metrics:nil views:viewDictionary];
NSArray *constraint_POS_V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-30-[redView]"
                                                                    options:0
                                                                    metrics:nil
                                                                      views:viewDictionary];

NSArray *constraint_POS_H = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[redView]"
                                                                    options:0
                                                                    metrics:nil
                                                                      views:viewDictionary];
[self.redView addConstraints:constraints_H];
[self.redView addConstraints:constraints_V];
[self.redView addConstraints:constraint_POS_V];
[self.redView addConstraints:constraint_POS_H];

Answer