2015-04-01 135 views
3

我探索了現有的Q &與SO有關的這個問題,但沒有找到我的答案。自定義的UITableviewcell高度設置不正確

我知道這是由tableview在運行時不知道自定義單元的高度引起的,但不知道如何克服這個問題。這是的iOS 8 +的Xcode 6.我做了所有的自動佈局所需的方法爲自定義小區的固有大小...

    在代碼創建爲
  • 標準的tableview與標準單元中,只有一個(行= 2)定製單元格;

    customCell:

    -(CGSize)intrinsicContentSize 
    

    { //用於測試目的硬編碼

    return CGSizeMake(500.0, 450.0); 
    

    }

    在iOS模擬器運行時
  • ,發現該customCell顯示 「下面」 等與其高度標準相同的方式設置其他標準​​單元高度,而不是其高度設置得更大比其他細胞。

在表視圖控制器:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell; 
    pageViewCellTableViewCell* customCell; 

    if (indexPath.row != 2) 
    { 
     cell = [tableView dequeueReusableCellWithIdentifier:@"regularCell" forIndexPath:indexPath]; 


     cell.textLabel.text = [NSString stringWithFormat:@"Table Row %lu", indexPath.row]; 
     return cell; 
    } 
    else 
    { 
     customCell = [tableView dequeueReusableCellWithIdentifier:@"customCell"] ; 

     if (customCell == nil) { 

      customCell = [[customCell alloc] init]; 

     } 

     customCell.parentViewController = self; 


     [customCell setNeedsUpdateConstraints]; 
     [customCell setNeedsLayout]; 
     [customCell setNeedsDisplay]; 


     return customCell; 

    } 

    return nil ; 
} 

- (CGFloat)tableView: (UITableView*)tableView EstimatedHeightForRowAtIndexPath: (NSIndexPath*) indexPath 
{ 
    if (indexPath.row != 2) 
     return 10; 
    else 
     return 450; 
} 

- (CGFloat)tableView: (UITableView*)tableView HeightForRowAtIndexPath: (NSIndexPath*) indexPath 
{ 
    if (indexPath.row != 2) 
     return 10; 
    else 
     return 450; 
} 

當模擬器運行:

得到了以下錯誤消息: 一次僅警告:檢測到的情況下的約束含糊建議0高度爲tableview單元格的內容視圖。我們正在考慮無意的崩潰並使用標準高度。

screenshot of simulator, see Row 2 got tucked under other rows<code>enter code here</code>

回答

2

想通了。

按照WWDC 2014的視頻 「有什麼新的泰伯維和收藏觀」:

  1. 添加從self.view約束customTableViewCell.contentView
  2. 集intrinsicSize到self.bounds.size
5

幾天前我遇到過類似的錯誤。我建議你再次檢查自動佈局約束。

設置tableView.rowHeight = UITableViewAutomatic時,您必須確保單元格中的每個元素都具有領先的頂部&底部約束。否則,swift無法根據內容大小動態更改高度。

+2

這有幫助 - 也調整約束的優先級(並使用<=)可以幫助避免一旦添加所有約束時衝突約束的不同錯誤。 – Speedy99 2016-11-19 00:47:01

1

我剛纔也談到了這一點。我正在從一個nib文件做一個自定義的tableViewCell,而不是使用storyboard單元格。我添加了上面建議的代碼(Objective-C):

self.tableView.rowHeight = UITableViewAutomaticDimension; 
[self.tableView setEstimatedRowHeight:85.0]; 

沒有幫助。 做了什麼幫助解決了我的約束。我認爲通過固定到頂部,然後設置下兩個物體之間的垂直間距就足夠了。我還爲UILabels設定了一個固定的高度限制,這會有所幫助。它沒有。去除任何固定高度的限制並將底部物體固定到容器底部可解決此問題。原來,自動佈局比我聰明。誰知道!?大聲笑

相關問題