UITabelView的Cell自适应高度

http://www.jianshu.com/p/83e72f90d7c1

思路:因为cell高度不固定,需要动态赋值,所以用了最常见的cell内有一个model,model内有cellHeight的方式,在cell的model的set方法中给model的cellHeght赋值。

cell.m  (重写model属性的set方法)

-(void)setBaikeModel:(Model *)baikeModel{

    self.titleLabel.text = baikeModel.title;

    self.titleLabelHeightConstraint.constant = baikeModel.cellHeight;

}

model.m  (重写title属性的set方法)

-(void)setTitle:(NSString *)title{

    _title = title;

    //根据后台数据,动态计算cell高度

    CGFloat height = [title heightWithFont: [JYEToolModel jyeFontWithName:@"PingFangSC-Regular" size:16] withinWidth:ScreenWidth - 30];

    _cellHeight = height;

}

VC.m

需要注意cell高度

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

    Model *baikeModel = [self.contentArray objectAtIndex:indexPath.row];

    return baikeModel.cellHeight + 12+11+20;

}

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

    return 70;

}

补充小工具:

#pragma mark -根据宽度,字号来计算字符串的高度

- (float) heightWithFont: (UIFont *) font withinWidth: (float) width{

    CGRect textRect = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT)

                                         options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading

                                      attributes:@{NSFontAttributeName:font}

                                         context:nil];

    return ceil(textRect.size.height);

}

#pragma mark -根据字号来计算字符串的宽度

- (float) widthWithFont: (UIFont *) font{

    CGRect textRect = [self boundingRectWithSize:CGSizeMake(MAXFLOAT, font.pointSize)                 options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading

                                      attributes:@{NSFontAttributeName:font}

                                         context:nil];

    return ceil(textRect.size.width);

}

#pragma mark -根据字符串的实际高度、行间距来计算新的字符串的高度

-(float) realHeightWithDefaultHeight:(float)defaultHeight withRowSpacing:(float)rowSpacing withFont:(UIFont *)font{

    CGFloat oneRowHeight = [@"test" sizeWithAttributes:@{NSFontAttributeName:font}].height;

    CGFloat rows = defaultHeight/oneRowHeight;

    CGFloat realHeight = defaultHeight +(rows - 1)* rowSpacing;

    return realHeight;

}

#import "JYEToolModel.h"

@implementation JYEToolModel

/*

 *  自定义字号大小

 */

+(UIFont *)jyeFontWithName:(NSString *)name size:(CGFloat)size{

    UIFont * font = nil;

    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 9){

        font = [UIFont fontWithName:name size:size];

    }else{

        if([name rangeOfString:@"Medium"].location == NSNotFound){

            font = [UIFont systemFontOfSize:size];

        }else{

            font = [UIFont boldSystemFontOfSize:size];

        }

    }

    return font;

}

@end

原文地址:https://www.cnblogs.com/lrr0618/p/7235329.html