根据文本计算size

.h文件

+ (CGSize)sizeForString:(NSString *)string
                   limitSize:(CGSize)sz
                          font:(UIFont *)ft
          lineBreakMode:(NSLineBreakMode)lineBreakMode
                 alignment:(NSTextAlignment)alignment;

.m 文件

+ (CGSize)sizeForString:(NSString *)string
          limitSize:(CGSize)sz
               font:(UIFont *)ft
      lineBreakMode:(NSLineBreakMode)lineBreakMode
          alignment:(NSTextAlignment)alignment {

CGSize  boundSize = CGSizeMake(sz.width, sz.height);
CGSize  resultSize      = CGSizeZero; 

if ([NSString instancesRespondToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineBreakMode = lineBreakMode;
    style.lineSpacing   = 0;
    style.alignment     = alignment;
    
    NSDictionary *attribute = @{NSFontAttributeName:ft,
                                NSParagraphStyleAttributeName:style};
    CGRect rect = [string boundingRectWithSize:boundSize
                                       options:NSStringDrawingUsesLineFragmentOrigin
                                    attributes:attribute
                                       context:nil];
    resultSize = CGSizeMake(ceil(rect.size.width), ceil(rect.size.height));
}else {
    resultSize = [string sizeWithFont:ft
              constrainedToSize:boundSize
                  lineBreakMode:lineBreakMode];
}

resultSize = CGSizeMake(MIN(sz.width,resultSize.width),
                  resultSize.height);
return resultSize;
    }

你可能感兴趣的:(根据文本计算size)