1

我正在尝试在 iOS 6 中使用约束并希望将标签与另一个对齐。一个标签和约束是在点击按钮时动态创建的。这是一个非常简单的例子,但我得到一个有线错误,我不知道是什么原因。

编码:

- (IBAction)addToLog:(UIButton *)sender {
UILabel *labelLastTime = [[UILabel alloc]initWithFrame:CGRectMake(20, 359, 92, 42)];
labelLastTime.text = [NSString stringWithFormat:@"%@kg x %@", self.selectedPickerWeight, self.selectedPickerRepetitions];

labelLastTime.font = [UIFont boldSystemFontOfSize:17.0];
labelLastTime.textAlignment = NSTextAlignmentCenter;
labelLastTime.textColor = [UIColor colorWithRed:133.0/255.0 green:133.0/255.0 blue:133.0/255.0 alpha:1.0];

labelLastTime.backgroundColor = [UIColor colorWithRed:228.0/255.0 green:228.0/255.0 blue:228.0/255.0 alpha:1.0];
labelLastTime.layer.borderColor = [UIColor colorWithRed:185.0/255.0 green:185.0/255.0 blue:185.0/255.0 alpha:1.0].CGColor;
labelLastTime.layer.borderWidth = 1;
labelLastTime.layer.cornerRadius = 5;

[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:labelLastTime];


NSLayoutConstraint *cn = [NSLayoutConstraint constraintWithItem:labelLastTime
                                                       attribute:NSLayoutAttributeTop
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:self.labelTodayVsLastTime
                                                       attribute:NSLayoutFormatAlignAllBottom
                                                      multiplier:1.0
                                                        constant:5.0];

[self.view addConstraint:cn];

}

错误:

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“无法在 descriptionForLayoutAttribute_layoutItem_coefficient 中创建描述。有些东西是零

当我应用约束时发生错误,而不是在我设置它时。我之前设置了一个断点

[self.view addConstraint:cn]

当我检查结果时,我得到这 4 的 nil 值

container, markerAndPositiveExtraVar, negativeExtraVar and _flange
4

1 回答 1

2
NSLayoutConstraint *cn = [NSLayoutConstraint constraintWithItem:labelLastTime
  attribute:NSLayoutAttributeTop
  relatedBy:NSLayoutRelationEqual
  toItem:self.labelTodayVsLastTime
  attribute:NSLayoutFormatAlignAllBottom
  multiplier:1.0
  constant:5.0];

我遇到了同样的问题,约束定义略有不同,原因是 Xcode 自动完成问题。

看看第二attribute:行。您可能想要类似attribute: NSLayoutAttributeBottom.

NSLayoutFormatAlignAllBottom用于构建一个NSLayoutFormatOptions位掩码以提供给类似constraintsWithVisualFormat:options:metrics:views:.

于 2013-06-13T12:55:11.203 回答