【发布时间】:2019-08-12 17:45:33
【问题描述】:
当我扩展我的 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];
【问题讨论】:
-
给我们看一些代码。在这条线之前会发生什么?
-
我没有看到 addEdgeConstraint 的实现的猜测是 self.scrollView.subviews.firstObject 是 nil。您应该能够单步执行并确认。
-
@R4N 是的,它为零。
-
@user1285402 您应该以某种方式防止将约束添加到为 nil 的视图中。我假设 addEdgeConstraint: 在内部调用 NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant 如果其中一项为 nil,则会失败并显示您发布的错误
-
@R4N 是的,它在内部调用 NSLayoutConstraint..你能帮我解决这个问题吗
标签: ios objective-c nslayoutconstraint autolayout