2014-03-13 42 views
7

我有點難以確定如何正確定義在給定視圖被移除時會摺疊視圖之間的空間的約束。我曾嘗試添加具有大於或等於關係的垂直約束,但是,似乎不滿足約束條件的最小距離不是首選。例如,給定具有三個約束V:[A] -5 [B],V:[B] -5- [C]和V:[A] - (> = 5)的以下佈局, - [C]:Autolayout在刪除中間視圖時會摺疊空間

[ View A ] 
    | 
    5 pt 
    | 
[ View B ] 
    | 
    5 pt 
    | 
[ View C ] 

刪除視圖後BI希望它看起來是這樣的:

[ View A ] 
    | 
    5 pt 
    | 
[ View C ] 

但它看起來是這樣的:

[ View A ] 
    | 
    5 pt + 5 pt + height of view B 
    | 
[ View C ] 
+4

+1爲清晰整齊的格式化問題 – Eugene

+0

您是刪除視圖B還是隱藏它?你需要在某個時候恢復它嗎? –

回答

3

如果你正在尋找這個可擴展的,你可能需要在代碼中做到這一點。我使用類似

UIView *superView = /* whatever the superview of your views is, probably self.view in a lot of cases */ 
NSArray *arrViews = [NSArray arrayWithObjects:/* put only the things you want to show in here, do not put the hidden things, and put them in order from top to bottom */, nil]; 
CGFloat buffer = 5; 

[superView addConstraint:[NSLayoutConstraint constraintWithItem:[arrViews objectAtIndex:0] attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeTop multiplier:1 constant:buffer]]; 
for (int i = 1; i < arrViews.count; i++) 
{ 
    [superView addConstraint:[NSLayoutConstraint constraintWithItem:[arrViews objectAtIndex:i] attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:[arrViews objectAtIndex:i-1] attribute:NSLayoutAttributeBottom multiplier:1 constant:buffer]]; 
} 
[superView addConstraint:[NSLayoutConstraint constraintWithItem:[arrViews lastObject] attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeBottom multiplier:1 constant:-1*(buffer)]]; 

這將會把一個固定的間隔(尺寸= buffer)頂部的項目之間,它的上海華,那麼每個子視圖和子視圖之間直接上面,然後底部視圖和上海華之間。每次從arrViews中刪除一個項目,然後致電[superView needsLayout],您都必須打電話給您。您還需要確保以某種方式設置高度限制,否則您會收到錯誤。如果一切都將是相同的高度,你可以在循環中添加另一條線以添加高度約束。

8

您可以添加五:[A ] - 5 - [C]與愛人的優先權,下面1000

[superview] 
    | 
[ View A ] 
    |    | 
    5 pt (1000) | 
    |    | 
[ View B ]  5 pt (999) 
    |    | 
    5 pt (1000) | 
    |    | 
[ View C ]   
+0

此方法將垃圾郵件「無法同時滿足約束」。警告。另一個缺點是它不能很好地擴展垂直添加的視圖。 –

+0

@JackRowlingson剛剛用這種方法構建了一個測試項目 - 沒有警告。看起來你有其他一些衝突的限制。猜想你已經把View C以某種方式捕捉到了底部。 –

1

您需要重新連接程序的約束,使View C的約束View BView A代替,並從View AView B被刪除確保約束。 完成此操作後,請在包含這些視圖的超級視圖上調用layoutIfNeeded