2014-07-24 196 views
0

我正在创建一个类似Facebook的应用程序。我想根据内容调整单元格的高度。 tableviewcell由UIImageView,UILabelUIButton组成。我可以通过使用heightForRowAtIndexPath委托来调整单元格的高度,但是,有时候某个单元格中没有图像。根据内容调整tableviewcell高度

据我所知,heightForRowAtIndexPath是第一次被调用。所以,我无法传递在cellForRowAtIndexPath中计算的物体高度。

我想知道我是否可以通过heightForRowAtIndexPath内部cellForRowAtIndexPath的对象高度。

回答

0

通常,单元格中图像预览的高度是固定的。你可以在heightForRowAtIndexPath中计算单元格的高度。

如果您要使用动态图像大小,当您请求单元格的对象时,您应该从API接收图像高度。在这种情况下,您也可以在heightForRowAtIndexPath中计算单元格的高度。

或者您可以先下载图像并从UImage检索高度。

通常,我在我的应用程序中使用第二种或第一种情况。

0

正确的解决方案是:

添加@property (strong, nonatomic) MyCell* prototypeCell;到控制器。

创建一个getter:

- (MyCell*) prototypeCell { 
    if (!_prototypeCell) { 
    _prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:@"MyCell"]; 
    } 

return _prototypeCell; 
} 

移动的所有代码,相关单元配置从cellForRow到Cell类(你可以在这里看看:How to access properties in multiple custom tableviewcells

修改heightForRow:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; 
    return size.height+1; 
} 

适用于自动布局。如果您没有启用自动布局功能 - 您可以手动计算。

为了改善iOs7使用性能:

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath { 

    return 300; // or any number based on your estimation 
} 
0

heightForRowAtIndexPath首先调用。在这里你必须检查该特定indexPath中的单元格是否具有图像并相应地设置高度。你还没有提供任何代码。但是,假设你有一个用于填充的tableView所需的图像和字符串对象的数组,代码应该看起来有点像这样:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    CustomObject *object = (CustomObject *)[arrayOfObjects objectAtIndex:indexPath.row]; 
    if (object.cellImage != null) { 
     return 60; //height for row that has image; 
    } 
    return 44; //those without image 
} 
0

不,你不能,是快速的答案。

较慢的答案是在加载任何单元格之前调用高度(或估计的高度)方法。在iOS8之前,您需要分别进行高度计算。

从iOS8开始,表格将能够使用Autolayout来导出单元格高度 - 请参阅WWDC 2014的表格和集合视图中的新增功能。

相关问题