2011-11-18 80 views
1

我試圖返回heightForRowAtIndexPath委託方法中detailTextLabel的高度。這樣我的表格視圖單元應該和我的detailTextLabel一樣高。設置UITableViewCell的正確高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

    NSString *text = cell.detailTextLabel.text; 
    CGSize size = cell.detailTextLabel.bounds.size; 
    UIFont *font = cell.detailTextLabel.font; 

    CGSize labelSize = [text sizeWithFont:font       
         constrainedToSize:size 
          lineBreakMode:UILineBreakModeWordWrap]; 
    return labelSize.height; 
} 

但是我在下面的行得到一個EXC_BAD_ACCESS

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

WATS錯上面這段代碼?

+0

'-tableView:heightForRowAtIndexPath:'在'-tableView:cellForRowAtIndexPath:'過程中被調用,所以當你調用'-cellForRowAtIndexPath:'時,單元還沒有被完全創建,所以你不能引用它。 –

+0

[如何訪問tableView中的cell.textLabel.text:heightForRowAtIndexPath:from tableView:cellForRowAtIndexPath:](http://stackoverflow.com/questions/3903136/how-to-access-cell-textlabel-text-in -tableviewheightforrowatindexpath-from-tab)以及許多其他許多 – jrturton

回答

2

問題是在cellForRowAtIndexPath之前調用heightForRowAtIndexPath。所以這個單元還沒有被創建。

如果所有行都具有相同的高度,則可以爲該表指定一個公共高度。在您的viewDidLoad中,您可以僅說self.tableView.rowHeight = ABC;您也可以在「界面」構建器中對其進行設置。

2

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

應該

UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath]; 

但是,這將導致進入tableView:cellForRowAtIndexPath:幾個電話,更好的辦法:寫一個輔助方法,計算每個indexPath的身高,從叫它tableView:heightForRowAtIndexPath:tableView:cellForRowAtIndexPath:,保存高度將索引保存在以indexpathes作爲關鍵字的字典中,並且只計算高度,id indexPath不存在(或者某些方法需要重新計算)。返回高度。

相關問題