美文网首页
iOS文本高度的计算

iOS文本高度的计算

作者: 逐水而上 | 来源:发表于2016-05-30 11:59 被阅读2397次

    之前一直以为,单行文字的高度等于font的大小,也没有细细研究,好吧,其实这种想当然的认识是极其不正确的,还是需要通过方法进行计算。

    单行文本高度的计算方法

    -(CGFloat)singLineTextSize{
        CGFloat height = 0;
        height = [@"这是一个单行文本。" sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15.0]}].height;
        return height;
    }```
    NSLog可以看出文本高度是17.9,跟字体大小15.0还是差的挺多的。
    ####多行文本高度的计算方法
    

    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;
      }```

    相关文章

      网友评论

          本文标题:iOS文本高度的计算

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