2013-06-21 65 views
9

使用自動佈局時,我的理解是刪除子視圖(當然要保留對其的引用),但刪除的子視圖仍然知道其自動佈局約束。使用自動佈局去除和重新添加子視圖

但是,稍後將其添加回超級視圖時,子視圖不再知道其幀大小。相反,它似乎得到一個零框架。

我認爲autolayout會自動調整它的大小來滿足約束條件。情況並非如此嗎? 我認爲自動佈局意味着不要混淆幀rects。添加子視圖時是否仍然需要設置初始框架矩形,即使使用自動佈局?

回答

16

刪除子視圖時,與該子視圖相關的所有約束都將丟失。如果您以後需要再次添加子視圖,那麼您必須再次向該子視圖添加約束。

通常,我在我的自定義子視圖中創建約束。例如:

-(void)updateConstraints 
{ 
    if (!_myLayoutConstraints) 
    { 
     NSMutableArray *constraints = [NSMutableArray array]; 

     // Create all your constraints here 
     [constraints addWhateverConstraints]; 

     // Save the constraints in an ivar. So that if updateConstraints is called again, 
     // we don't try to add them again. That would cause an exception. 
     _myLayoutConstraints = [NSArray arrayWithArray:constraints]; 

     // Add the constraints to myself, the custom subview 
     [self addConstraints:_myLayoutConstraints]; 
    } 

    [super updateConstraints]; 
} 

updateConstraints將由Autolayout運行時自動調用。上面的代碼出現在您的自定義子類UIView中。

你說得對,在與Autolayout合作時,你不想觸摸框架尺寸。相反,只需更新updateConstraints中的約束即可。或者,更好的是,設置約束條件,因此您不必這樣做。

發現該主題的我的回答:

Autolayout UIImageView with programatic re-size not following constraints

不需要設置初始框架。如果您確實使用initWithFrame,請將其設置爲CGRectZero。您的約束將 - 事實上,必須是 - 詳細說明應該有多大的東西,或者其他意味着運行時可以推斷出大小的關係。

例如,如果您的可視格式爲:@"|-[myView]-|",那麼這就是橫向維度所需的所有內容。 Autolayout將知道尺寸爲myView以達到由|表示的父superview的界限。它太酷了。

+1

謝謝。這很好,很清楚。有一點需要注意的是,我問了Cocoa而不是Cocoa-touch,但是對於其他人來說,這些API(如Apple的Peter Ammon所描述的)相同或者幾乎相同。兩個世界的方法應該是一樣的。 – uchuugaka

+1

對不起,我錯過了。好點 –

+1

[文檔](https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instm/UIView/updateConstraints)說這是**重要**調用'[super updateConstraints]'作爲您實現的最後一步。它應該在你的方法的最後,而不是在開始。 – Eric

相關問題