2011-11-18 78 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不存在(或者某些方法需要重新计算)。返回高度。

相关问题