UITableView高度动态计算


阅读目录

  1. 传统frame布局下UITableViewCell 高度计算
  2. AutoLayout下UITableViewCell高度计算(iOS6、7)
  3. AutoLayout下UITableViewCell高度计算(iOS8)

1.传统frame布局下UITableViewCell 高度计算

主要是在UITableViewCell(subCell)中使用一个静态方法传入数据并手动计算内容的高度.
说到手动计算内容的高度,其实在cell里面大多是计算一些UILabel具体的宽高,根据内容计算UILabel对应的宽高,模拟代码:

+ (CGFloat)calulateHeightWithtTitle:(NSString*)title
{
    CGFloatheight =20;
    CGSizelabelSize = [titlesizeWithFont:[UIFont   systemFontOfSize:17]       
  constrainedToSize:CGSizeMake(300,500)];
    height = height + labelSize.height;
    returnheight;
}
//调用
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
     return [HomeCell  calulateHeightWithtTitle:self.dataArray[indexPath.row]];
}

2.AutoLayout下UITableViewCell高度计算(iOS6、7)

对高度进行了缓存

+ (instancetype)aTopicReplyCell
{
    GMFMShopTopicDetailCommentCell *bar = [[GMFMShopTopicDetailCommentCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"GMFMShopTopicDetailCommentCell"];
    return bar;
}

+ (CGFloat)heightWithReply:(GMBTopicReply *)reply
{
    if (reply.heightForCell) {
        return reply.heightForCell.floatValue;
    }
    GMFMShopTopicDetailCommentCell *cell = [GMFMShopTopicDetailCommentCell aTopicReplyCell];
    cell.reply = reply;
     cell.contentLab.preferredMaxLayoutWidth = kScreenWidth-80;
    CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    reply.heightForCell = @(size.height+1);
    return size.height+1;//由于是在cell.contentView上调用这个方法,那么返回的值将是contentView的高度,UITableViewCell的高度要比它的contentView要高1,
}
//调用
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [GMBTopicReplyCell heightWithReply:self.reply];
}

3. AutoLayout下UITableViewCell高度计算(iOS8下新特性)

self.tableView.estimatedRowHeight=44.0;
self.tableView.rowHeight=UITableViewAutomaticDimension;

4.其它

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容