富文本 iOS swift OC 计算高度

作者: littleGG 发布时间: 2019-08-08 浏览: 1005 次 编辑

OC版本

- (NSMutableAttributedString *)getAttributedStringForText:(NSString *)text font:(UIFont *)font
{
    NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:text];
    
   NSMutableDictionary *mutableAttributes = [self getMutableAttributes:font];
    
    [mutableAttributedString addAttributes:mutableAttributes range:NSMakeRange(0, [mutableAttributedString length])];
    
    return mutableAttributedString;
}

- (NSMutableDictionary *)getMutableAttributes:(UIFont *)font
{
    NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionary];
    
    [mutableAttributes setObject:font forKey:(NSString *)kCTFontAttributeName];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentLeft;
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.lineSpacing  = 3.;
    [mutableAttributes setObject:paragraphStyle forKey:(NSString *)kCTParagraphStyleAttributeName];
    return mutableAttributes;
}

计算高度

- (CGFloat)mDetailLabelHeitht:(NSString *)detailLabelStr :(NSF){    if (![detailLabelStr isKindOfClass:[NSString class]]) {
        detailLabelStr = @"";
    }    NSString *stringTotal = [detailLabelStr stringByReplacingOccurrencesOfString:@"    " withString:@"\t"];    
    CGSize size = [stringTotal boundingRectWithSize:CGSizeMake((SCREEN_BOUNDS - 20.0-25.0), CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:[self getMutableAttributes:self.mDetailLabel.font] context:nil].size;    
    return size.height;
}

swift 版本

 let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: str)
        let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .justified
        paragraphStyle.lineBreakMode = .byWordWrapping
        paragraphStyle.lineSpacing = 4.0
        
        attributedString.addAttributes([.font : UIFont.systemFont(ofSize: 15), .paragraphStyle: paragraphStyle], range: NSMakeRange(0, str.count))

计算高度

func height(text: String) -> CGFloat {        // 注意这里的宽度计算,要根据自己的约束来计算
        let maxSize = CGSize(width: (WIDTH() - 30), height: CGFloat(MAXFLOAT))
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .justified
        paragraphStyle.lineBreakMode = .byWordWrapping
        paragraphStyle.lineSpacing = 4.0
        let labelSize = NSString(string: text).boundingRect(with: maxSize,
                                                            options: [.usesFontLeading, .usesLineFragmentOrigin],
                                                            attributes:[.font : UIFont.systemFont(ofSize: 15), .paragraphStyle: paragraphStyle],
                                                            context: nil).size        
        return labelSize.height
}