2014-03-24 36 views
0

我有一個包含標題的視圖。此標題有4個視圖,顯示右側的圖像。我稱他們爲圖標,因爲他們每個人都會顯示或畫出一個字形。根據數據的不同,圖標2,3或4可能隱藏給我六種可能的組合。 即使隱藏,每個不可見的圖標也佔據其空間,在可視化中出現一個或多個「洞」。 這就是我現在使用的。隱藏一個或多個視圖時使用自動佈局移動UIViews

[header addSubview:_label]; 
[header addSubview:_icon1]; 
[header addSubview:_icon2]; 
[header addSubview:_icon3]; 
[header addSubview:_icon4]; 


NSDictionary *headerViewDict = NSDictionaryOfVariableBindings(_label, _icon1, _icon2, _icon3, _icon4); 

[header addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-2-[_label]-0-[_icon4(>=0,14)]-1-[_icon3(>=0,14)]-1-[_icon2(>=0,14)]-1-[_icon1(14)]-2-|" options:nil metrics:nil views:headerViewDict]]; 
[header addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_label]|" options:nil metrics:nil views:headerViewDict]]; 
[header addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_icon1]|" options:nil metrics:nil views:headerViewDict]]; 
[header addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_icon2]|" options:nil metrics:nil views:headerViewDict]]; 
[header addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_icon3]|" options:nil metrics:nil views:headerViewDict]]; 
[header addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_icon4]|" options:nil metrics:nil views:headerViewDict]]; 

我剛讀(https://stackoverflow.com/a/18066138/1360888),要解決這個有兩種可能過度約束或更改不變。 我對自動佈局非常陌生,而且我總是使用可視化格式語言(因爲我只用代碼構建了我的視圖),所以我不知道如何將該解決方案應用於我的案例。

如何爲我的視圖創建流體佈局?

注意:在我的應用程序中,我有很多視圖,如同時顯示標題,因此性能很重要。

+0

您鏈接的問題是試圖讓圖標占用的空間刪除的意見,在你的情況下,如果你只是隱藏,我會的認爲這會奏效。你看到什麼行爲? –

+0

如果我隱藏了一個圖標,我將只在圖標位置獲得空白區域。 – giampaolo

回答

0

我會做的是創建一個圖標數組(如你稱之爲UIImageViews?)。然後根據您的數據更新數組的內容。

在ViewWillLayoutSubviews

  1. 檢查陣列[1,2,3,4]
  2. 根據內容陣列中刪除所有約束
  3. 設置新的限制。這裏重要的是檢查數組的元素爲零。 Autolayout不會正確處理nil元素並失敗。

消除限制:

//Clear the constraints 
for (NSLayoutConstraint *constraint in [self.view constraints]) { 
    [self.view removeConstraint:constraint]; 
} 

添加約束:

if (myCustomView) {//constraintsWithVisualFormat does not support handling nil 
    //Add constraints for myCustomView Here 
} 

ViewWillLayoutSubviews

/** 
* Update the constraints before laying subviews 
* 
*/ 
- (void) viewWillLayoutSubviews 
{ 
    [super viewWillLayoutSubviews]; 

    //Remove constraints 

    //Set new constraints 

} 
相關問題