2013-06-26 153 views
19

我正在處理一個ios應用程序。我將自動佈局以編程方式添加到2個標籤。ios自動佈局:以編程方式設置寬度約束

我需要添加一個約束,使他們相等的寬度。

我知道如何使用固定標籤寬度:

constraint = [NSLayoutConstraint 
    constraintWithItem:myLabel 
      attribute:NSLayoutAttributeWidth 
      relatedBy:NSLayoutRelationEqual 
       toItem: nil 
      attribute:NSLayoutAttributeNotAnAttribute 
      multiplier:1.0f 
      constant:200.0f]; 

這將修復標籤大小設置爲常。但我有兩個標籤,我希望它們具有相同的大小,而不必設置常量。

回答

16

原來,我只需要做到以下幾點:

constraint = [NSLayoutConstraint 
    constraintWithItem:myLabel 
     attribute:NSLayoutAttributeWidth 
     relatedBy:NSLayoutRelationEqual 
      toItem: otherLabel 
     attribute:NSLayoutAttributeWidth 
     multiplier:1.0f 
     constant:0]; 
+2

爲什麼你需要一個toItem:otherLabel? –

+0

的想法是使「myLabel」和「otherLabel」的寬度相等。所以我把它們中的一個放在「withItem」中,另一個放在「otherItem」中 – Youssef

+2

如果我只想爲myLabel添加寬度限制,該怎麼辦?我會爲「toItem」做些什麼。我嘗試了零,但這並沒有太大的作用。謝謝 –

相關問題