Search code examples
iosobjective-cnslayoutconstraintautolayout

When I extend my UIViewController I'm getting NSLayoutConstraint error


When I'm extending my UIViewController and calling the extended ViewController I'm getting : Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'NSLayoutConstraint for (null): Constraint must contain a first layout item' error.

 CGSize size = CGSizeMake(142, 200);
    [self.scrollView.subviews enumerateObjectsUsingBlock:^(UIView* subView, NSUInteger i, BOOL *stop) {
        subView.translatesAutoresizingMaskIntoConstraints = NO;
        [ViewHelper addWidthConstraint:subView width:size.width];
        [ViewHelper addHeightConstraint:subView height:size.height];
        if (i < self.scrollView.subviews.count - 1) {
            [ViewHelper addHorizontalConstraint:self.scrollView
                                     previouseView:subView
                                          nextView:(UIView*)self.scrollView.subviews[i + 1]
                                            spacer:8];
        }

        [ViewHelper addEdgeConstraint:NSLayoutAttributeTop
                               superview:self.scrollView
                                 subview:subView];

        [ViewHelper addEdgeConstraint:NSLayoutAttributeBottom
                               superview:self.scrollView
                                 subview:subView];

    }];

    [ViewHelper addEdgeConstraint:NSLayoutAttributeLeft
                           superview:self.scrollView
                             subview:self.scrollView.subviews.firstObject];

    [ViewHelper addEdgeConstraint:NSLayoutAttributeRight
                           superview:self.scrollView
                             subview:self.scrollView.subviews.lastObject];

    [ViewHelper addHeightConstraint:self.scrollView height:size.height];

Crashing at this line:

[ViewHelper addEdgeConstraint:NSLayoutAttributeLeft
                               superview:self.scrollView
                                 subview:self.scrollView.subviews.firstObject];

Solution

  • The error indicates that you're attempting to add a constraint using a view which is nil. You should guard against one the self.scrollView.subviews.firstObject/lastObject being nil before attempt to add the constraints to them (by making sure the scrollView has any subviews). Here's an example:

    // make sure that the scrollView has some subviews before attempting to add layout constraints using the subviews
    if ([self.scrollView.subviews count] > 0) {
        [ViewHelper addEdgeConstraint:NSLayoutAttributeLeft
                            superview:self.scrollView
                              subview:self.scrollView.subviews.firstObject];
    
        [ViewHelper addEdgeConstraint:NSLayoutAttributeRight
                            superview:self.scrollView
                              subview:self.scrollView.subviews.lastObject];
    }