美文网首页
利用YYLabel 富文本 动态计算Cell行高

利用YYLabel 富文本 动态计算Cell行高

作者: MccReeee | 来源:发表于2018-09-07 11:49 被阅读187次
  • 先看最终效果, 不同的Cell高度不同,被其中的内容所撑开


    image.png

将普通TableView分成 Controller Cell Model 三个类

  • Model
    Model 中放一个YYTextLayout属性


    image.png

在get方法中计算layout, 同时注意, 因为使用富文本, 所以label.font lable.textcolor等属性都需要通过富文本设置

@implementation CommentModel

- (YYTextLayout *)yyLayout{
    CGSize size = CGSizeMake(W-85, CGFLOAT_MAX);
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc]initWithString:self.commendcontent];
    NSRange range = NSMakeRange(0, self.commendcontent.length);
    
    [attString addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:15]} range:range];
    [attString addAttribute:NSForegroundColorAttributeName value:T333333 range:range];
    
    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:size text:attString];
    return layout;
}

@end
  • Controller
    在控制器的tableView代理方法中返回动态计算的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //动态计算cell高度
    CommentModel *comment = self.comments[indexPath.row];
    return comment.yyLayout.textBoundingSize.height + 130;
}
  • Cell
    最后将Model赋给Cell,在set方法中设置YYLabel的layout属性就可以了
- (void)setComment:(CommentModel *)comment{
    _comment = comment;

    self.comtLab.bounds = comment.yyLayout.textBoundingRect;
    self.comtLab.textLayout = comment.yyLayout;
    self.comtLab.lineBreakMode = NSLineBreakByCharWrapping;

}

相关文章

网友评论

      本文标题:利用YYLabel 富文本 动态计算Cell行高

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