计算文字高度

计算文字高度

  • label

     //定义label
        self.titleLabel = [[UILabel alloc] init];
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
            [style setLineSpacing:2];
            NSDictionary *dic = @{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Light" size:14], NSParagraphStyleAttributeName:style};
            NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:self.nameStr attributes:dic];
            self..titleLabel.attributedText = attributeStr;
            CGFloat height = [self getHeightLineWithString:self.nameStr withWidth:kScreenWidth - 30 withFont:[UIFont fontWithName:@"PingFangSC-Light" size:14]];
           self..titleLabel.frame =  CGRectMake(15, kNavgationHeight, kScreenWidth - 30, height);
    
  • 根据字符串计算label高度

    #pragma mark - 根据字符串计算label高度
    - (CGFloat)getHeightLineWithString:(NSString *)string withWidth:(CGFloat)width withFont:(UIFont *)font {
    
          //1.1最大允许绘制的文本范围
        CGSize size = CGSizeMake(width, 2000);
        //1.2配置计算时的行截取方法,和contentLabel对应
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setLineSpacing:2];
        //1.3配置计算时的字体的大小
        //1.4配置属性字典
        NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:style};
        //2.计算
        //如果想保留多个枚举值,则枚举值中间加按位或|即可,并不是所有的枚举类型都可以按位或,只有枚举值的赋值中有左移运算符时才可以
        CGFloat height = [string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size.height;
        return height;
    }
    

猜你喜欢

转载自blog.csdn.net/haixing_zfj/article/details/80235055