iOS学习之根据文本内容动态计算文本框高度的步骤

在视图加载的过程中,是先计算出frame,再根据frame加载视图的,所以在设计计算高度的方法的时候,设计成加号方法;

//首先给外界提供计算cell高度的方法
+ (CGFloat)heightForRowWithDic:(NSDictionary *)dic {
    //cell高度 = nameLabel高度 + contentLabel高度 + 间距;
    return [self heightForText:dic[@"content"]] + 30 + kHeight_NameLabel;
}

//动态计算文本高度
+ (CGFloat)heightForText:(NSString *)text {
    //1.创建计算文本高度的参考量
    //1.1 最大允许绘制的文本范围(尽量大点);
    CGSize maxSize = CGSizeMake(kWidth_ContentLabel, 2000);
    //1.2 配置计算时的行截取方式,要和contentLabel对应
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineBreakMode = NSLineBreakByCharWrapping;
    //1.3 配置计算时的字体大小
    UIFont *font = [UIFont systemFontOfSize:14];
    //1.4 配置属性字典
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:style};
    //计算
    //如果想保留多个枚举值,泽枚举值中间加按位或|即可,并不是所有的枚举值都可以按位或,枚举值的赋值中有左移运算符时才可以.
    CGFloat height = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size.height;
    
    return height;
    
}
在计算文本高度的时候,要给contentLabel设置一些属性

- (UILabel *)contentLabel {
    if (!_contentLabel) {
        self.contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(kMarginLeft_ContentLabel, kMarginTop_ContentLabel, kWidth_ContentLabel, kHeight_ContentLabel)];

        //对contentLabel进行一些设置
        _contentLabel.font = [UIFont systemFontOfSize:14];
        //设置Label可以多行显示,0表示没有限制行数
        _contentLabel.numberOfLines = 0;
        //设置断行模式
        _contentLabel.lineBreakMode = NSLineBreakByCharWrapping;//以单个字符进行截取.
    }
    return [[_contentLabel retain] autorelease];
}


 
原文地址:https://www.cnblogs.com/ErosLii/p/4496768.html