1. 程式人生 > >ios 富文字的高度

ios 富文字的高度

+ (CGFloat)getStrHeightWithAttributeStr:(NSAttributedString *)string
                                    viewWidth:(CGFloat)viewWidth{
    if (string.length == 0) {
        return 0;
    }
    
    CGSize size  = [string boundingRectWithSize:CGSizeMake(viewWidth, MAXFLOAT) options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  context:nil].size;
    return ceil(size.height);
}

+ (CGFloat)getStrWidthWithAttributeStr:(NSAttributedString *)string
                                  viewHeight:(CGFloat)viewHeight{
    if (string.length == 0) {
        return 0;
    }
    CGSize size  = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, viewHeight) options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    return ceil(size.width);
}

#import "LJSDAttributeLabel.h"

@implementation LJSDAttributeLabel

- (void)setAttributedText:(NSString*)text
              lineSpacing:(float)lineSpace
                    width:(float)width
                 fontSize:(float)fontSize{
    if (isEmptyStr(text)) return;
   
    self.numberOfLines = 0;
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:text];
    //設定行間距
    if (attrStr && attrStr.length > 0){
        NSMutableParagraphStyle *style = [attrStr attribute:NSParagraphStyleAttributeName atIndex:0 effectiveRange:nil];
        int  lineSpacing = lineSpace;
        if (style){
            style.lineSpacing = lineSpacing;
        }else{
            style = [[NSMutableParagraphStyle alloc]init];
            style.lineSpacing = lineSpacing;
            [attrStr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, attrStr.length)];
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize] range:NSMakeRange(0, attrStr.length)];
        }
        [self setAttributedText:attrStr];
        
        //富文字的高度
        self.contentHeight = [TFGoodsUtils getStrHeightWithAttributeStr:attrStr viewWidth:width];
    }
}

@end