美文网首页
UILabel和UITextView的宽、高、行数等

UILabel和UITextView的宽、高、行数等

作者: 深山问 | 来源:发表于2019-02-01 14:11 被阅读12次
    // 生成AttributeString
    -(NSAttributedString *)attributeWithLineSpace:(CGFloat)lineSpace font:(UIFont *)font color:(UIColor *)color withText:(NSString *)text{
        NSParameterAssert(font && color);
        if (text.length == 0) return nil;
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = lineSpace;  //设置行间距
        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
        paragraphStyle.alignment = NSTextAlignmentLeft;
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:font,NSForegroundColorAttributeName:color}];
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
        return [attributedString copy];
    }
    
    // 根据AttributeString计算高度
     NSAttributedString *explaintAtt = [self attributeWithLineSpace:8 font:[UIFont pf_MediumFontOfSize:14] color:HEX_RGBA(0x333331, 1) withText:_newsModel.explain];
    CGSize size =  [explaintAtt boundingRectWithSize:CGSizeMake(SCREEN_WIDTH() - 44 - 33 , MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    // 注意这里取整加1
     CGFloat height= ceil(size.height) + 1;
    

    相关文章

      网友评论

          本文标题:UILabel和UITextView的宽、高、行数等

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