天天看点

IOS聊天泡泡,根据内容计算宽度和高度(动态计算高度和宽度)

根据你的显示内容的最大宽度计算你的内容所需要的高度返回,

当你的内容达不到你设定的最大的宽度时,计算宽度返回。

其他不多数,上代码。

Factory.h

+ (CGFloat)textheight:(NSString *)string andFont:(UIFont *)fontsize andwidth:(CGFloat)numsize;

Factory.m

//根据字体计算 label 高度 numsize 字符串最小高度

+(CGFloat)textheight:(NSString *)string andFont:(UIFont *)fontsize andwidth:(CGFloat)numsize

{

    NSString *text = string;

    UIFont *font = fontsize;//跟label的字体大小一样

    CGSize size = CGSizeMake(numsize, MAXFLOAT);//跟label的宽设置一样

    //NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];

    //size = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:dic context:nil].size;

    size = [text boundingRectWithSize:size font:font maxWidth:numsize];

    return size.height;

}

NSString+StringFrame.h

#import <UIKit/UIKit.h>

@interface NSString (StringFrame)

- (CGSize)boundingRectWithSize:(CGSize)size font:(UIFont *)font;

- (CGSize)boundingRectWithSize:(CGSize)size font:(UIFont *)font maxWidth:(CGFloat)maxWidth;

@end

NSString+StringFrame.m

#import "NSString+StringFrame.h"

@implementation NSString (StringFrame)

- (CGSize)boundingRectWithSize:(CGSize)size font:(UIFont *)font;

{

    NSDictionary *attribute = @{NSFontAttributeName: font};

    CGSize reSize = [self boundingRectWithSize:size

                                             options:

                      NSStringDrawingTruncatesLastVisibleLine |

                      NSStringDrawingUsesLineFragmentOrigin |

                      NSStringDrawingUsesFontLeading

                                          attributes:attribute

                                             context:nil].size;

    return reSize;

}

- (CGSize)boundingRectWithSize:(CGSize)size font:(UIFont *)font maxWidth:(CGFloat)maxWidth

{

    NSArray *array = [self componentsSeparatedByString:@"\n"];

    array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        NSString *str1 = obj1;

        NSString *str2 = obj2;

        NSComparisonResult result;

        if (str1.length > str2.length)

        {

            result = NSOrderedAscending;

        }

        else if (str1.length < str2.length)

        {

            result = NSOrderedDescending;

        }

        else

        {

            result = NSOrderedSame;

        }

        return result;

    }];

    CGSize reSize = [array[0] boundingRectWithSize:size font:font];

    if (reSize.width > maxWidth)

    {

        reSize = [self boundingRectWithSize:CGSizeMake(maxWidth, MAXFLOAT) font:font];

    }

    else

    {

        reSize = [self boundingRectWithSize:CGSizeMake(reSize.width, MAXFLOAT) font:font];

    }

    return reSize;

}

@end

继续阅读