2012-12-26 50 views
1

我想在iOS 6中使用約束,並希望將標籤與另一個對齊。一個標籤和約束是在一個按鈕上點擊動態創建的。這是一個非常簡單的例子,但我得到一個有線錯誤,我不知道是什麼原因。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

container, markerAndPositiveExtraVar, negativeExtraVar and _flange 
+0

你檢查過以確保self.labelTodayVsLastTime有效嗎?我*想*第二個屬性是係數? – Padin215

回答

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

我有同樣的問題用一個稍微不同的約束定義和原因是一個Xcode自動完成snafu。

看看第二個attribute:一行。你可能想要像attribute: NSLayoutAttributeBottom這樣的東西。

NSLayoutFormatAlignAllBottom用於構建NSLayoutFormatOptions位掩碼給constraintsWithVisualFormat:options:metrics:views:之類的東西。

+0

謝謝我前一段時間解決它,但這是正確的答案:) –