2013-03-20 63 views
1

我有一個容器視圖,它位於主UIViewConroller的左側。此容器視圖由底部的幾個按鈕構成,中間的UITableView顯示用戶數據,另一個UITableView位於頂部,用於顯示選定的用戶數據。我想要這個頂級UITableView的行爲,使它在沒有選定數據的情況下消失,並且如果有的話達到最大高度200。每個選定的數據項將等同於表中的一個條目。與UITableView大小和NSLayoutConstraints戰鬥

查看圖片。在運行它的PIC,我已加載一個選定的數據項目名爲「測試」:

enter image description here enter image description here

我好歹是與那些由Interface Builder創建的佈局限制有問題。以下是我已經採取的動態重新調整數據表大小和選擇數據表的步驟。

我已經設置了最頂端的TableView是< = 200,左中間的一個作爲默認值,然後加到這個代碼做頂部的表的大小調整:

-(void)setSelectedFacets:(NSArray *)selectedFacets{ 
    _selectedFacets = selectedFacets; 
    [self.selectedFacetsTableView reloadData]; 

    CGRect frame = self.selectedFacetsTableView.frame; 
    frame.size.height = 10 ;//36 * selectedFacets.count; 
    self.selectedFacetsTableView.frame = frame; 
    [self.selectedFacetsTableView setNeedsDisplay]; 
    [self.view setNeedsDisplay]; 
} 

剪斷上面的代碼不執行(視圖控制器完全加載後),但對實際高度沒有影響。

有沒有人有這方面的經驗?

我知道你可以添加一個IBOutlet到NSLayoutConstraints(以獲得對它們的引用),然後在運行時刪除它們。這似乎是比應該更多的工作。我錯過了什麼嗎?

回答

0

如果您使用自動佈局,則不應設置框架。只添加/刪除/修改佈局約束。

通過使用「Pin」和「Align」等按鈕,確保您僅在IB中使用NSLayoutConstraints。做了的tableView高度源代碼訪問的約束:

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewHeightConstraint;

實際設置的高度應該是updateViewContraints

- (void)updateViewConstraints { 
    CGFloat height = MAX(200.0f, 36.0f * selectedFacets.count); 
    [self.tableView removeConstraint:self.tableViewHeightConstraint]; 
    NSLayoutConstraint *lc = [NSLayoutConstraint constraintWithItem:self.tableView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:height]; 
    [self.tableView addConstraint:lc]; 
    self.tableViewHeightConstraint = lc; 
    [super updateViewConstraints]; 
} 

setSelectedFacets:的片段只是叫[self updateViewConstraints]