计算文本高度

本文摘自http://www.jianshu.com/p/248c49153254
仅记录留作参考

单行文字的高度是不等于font的大小的,可以用下面的方式求出单行高度:
单行文本高度的计算方法

-(CGFloat)singLineTextSize{
    CGFloat height = 0;
    height = [@"这是一个单行文本。" sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15.0]}].height;
    return height;
}


多行文本高度的计算方法

NSMutableAttributedString *GetAttributedText(NSString *value) {//这里调整富文本的段落格式
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:value];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:8.0];
    //    [paragraphStyle setParagraphSpacing:11];  //调整段间距
    //    [paragraphStyle setHeadIndent:75.0];//段落整体缩进
    //    [paragraphStyle setFirstLineHeadIndent:.0];//首行缩进
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [value length])];
    return attributedString;
}
- (CGFloat)calculateMeaasgeHeightWithText:(NSString *)string andWidth:(CGFloat)width andFont:(UIFont *)font {
    static UILabel *stringLabel = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{//生成一个同于计算文本高度的label
        stringLabel = [[UILabel alloc] init];
        stringLabel.numberOfLines = 0;
    });
    stringLabel.font = font;
    stringLabel.attributedText = GetAttributedText(string);
    return [stringLabel sizeThatFits:CGSizeMake(width, MAXFLOAT)].height;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容