当我扩展我的 UIViewController 时,我收到 NSLayoutConstraint 错误

When I extend my UIViewController I'm getting NSLayoutConstraint error

当我扩展我的 UIViewController 并调用扩展的 ViewController 时,我得到:由于未捕获的异常 'NSInvalidArgumentException',正在终止应用程序,原因:'NSLayoutConstraint for (null): Constraint must contain a first layout item'错误。

 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];

在这一行崩溃:

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

该错误表明您正在尝试使用为 nil 的视图添加约束。在尝试向它们添加约束之前,您应该防止 self.scrollView.subviews.firstObject/lastObject 为 nil(通过确保 scrollView 具有任何子视图)。这是一个例子:

// 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];
}