美文网首页
iOS 代码计算cell高度自适应

iOS 代码计算cell高度自适应

作者: 木马不在转 | 来源:发表于2016-09-12 22:53 被阅读192次

    1.xib cell

    1 先 property cell

    @property (nonatomic, strong)  ZHCalculateTableViewCell *prototypeCell;

    2.获取cell

    self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    3.计算cell高度

    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

    {

    ZHCalculateTableViewCell *cell = self.prototypeCell;// 必须将对象传给一个新对象

    cell.contentView.translatesAutoresizingMaskIntoConstraints = NO;

    [self configureCell:cell atIndexPath:indexPath];//必须先对Cell中的数据进行配置使动态计算时能够知道根据Cell内容计算出合适的高度

    /*------------------------------重点这里必须加上contentView的宽度约束不然计算出来的高度不准确-------------------------------------*/

    CGFloat contentViewWidth = CGRectGetWidth(self.tableView.bounds);

    NSLayoutConstraint *widthFenceConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:contentViewWidth];

    [cell.contentView addConstraint:widthFenceConstraint];

    // Auto layout engine does its math

    CGFloat fittingHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    [cell.contentView removeConstraint:widthFenceConstraint];

    return fittingHeight+2*1/[UIScreen mainScreen].scale;//必须加上上下分割线的高度

    }

    2.Masonry

    1.第一种直接在cell里加一个加号方法

    +(CGFloat)heightWithModel:(TestModel*)model{

    TestCell*cell=[[TestCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:@""];

    [cellconfigCellWithModel:model];

    [celllayoutIfNeeded];

    CGRectframe=cell.descLabel.frame;

    returnframe.origin.y+frame.size.height+20;

    }

    2.用UITableView+FDTemplateLayoutCell计算
    git地址  https://github.com/yolii/Masonry-FDTemplateLayoutCell

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

    return [tableView fd_heightForCellWithIdentifier:kYLLayoutTableViewCell cacheByIndexPath:indexPath configuration:^(YLLayoutTableViewCell *cell) {

    [cell setFeed:[self.viewModel.feedArray objectAtIndex:indexPath.row]];

    }];

    }

    3.自适应,在cell里就把cell.contentView的大小约束对

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

    return UITableViewAutomaticDimension;

    }

    相关文章

      网友评论

          本文标题:iOS 代码计算cell高度自适应

          本文链接:https://www.haomeiwen.com/subject/yqtmettx.html