美文网首页
Object-C 计算文本的高度

Object-C 计算文本的高度

作者: Minoz_min | 来源:发表于2017-09-26 18:51 被阅读31次

    转载:@devchena 的swift方法转成Object-C方法:http://www.jianshu.com/p/0dd6141c46db (swift篇)

    计算文本高度

    + (CGFloat)heightText:(NSString *)text inWidth:(CGFloat)width font:(UIFont *)font
    {
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
        CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
        return ceilf(rect.size.height);
    }
    

    设置行间距时计算文本高度

    + (CGFloat)heightText:(NSString *)text inWidth:(CGFloat)width font:(UIFont *)font lineSpacing:(CGFloat)lineSpacing
    {
        NSMutableDictionary *mDictionary = [[NSMutableDictionary alloc] init];
        [mDictionary setObject:font forKey:NSFontAttributeName];
        [mDictionary setObject:[NSNumber numberWithInt:0] forKey:NSBaselineOffsetAttributeName];
        if (lineSpacing) {
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            paragraphStyle.lineSpacing = lineSpacing;
            [mDictionary setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
        }
        
        CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:mDictionary context:nil];
        
        CGFloat spacing = rect.size.height - font.lineHeight;
        if (spacing <= lineSpacing && spacing > 0) {
            return ceilf(font.lineHeight);
        }
        return ceilf(rect.size.height);
    }
    

    设置间距并限制显示行数时计算高度

    + (CGFloat)heightText:(NSString *)text inWidth:(CGFloat)width font:(UIFont *)font lineSpacing:(CGFloat)lineSpacing lines:(int)lines
    {
        if (lines < 0) {
            return 0;
        }
        
        CGFloat height = [self heightText:text inWidth:width font:font lineSpacing:lineSpacing];
        
        if (lines == 0) {
            return ceil(height);
        }
        
        CGFloat maximumHeight = font.lineHeight * lines + MAX(lineSpacing * (lines - 1), 10);
        if (height >= maximumHeight) {
            return ceilf(maximumHeight);
        }
        return ceilf(height);
    }
    

    DEMO: https://github.com/Minozmin/HHMTitleSizeDemo.git

    相关文章

      网友评论

          本文标题:Object-C 计算文本的高度

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