注意:
1.options 参数请使用:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
2.注意font和宽度的前后设置一致,特别是font的设置,默认label的font是17,如果在后面自己设置了font,那么不要忘记在label初始化的时候也设置统一一致。否则会出现如下结果(少些文字没法显示,左边是app上cell的显示,右边是实际的后台数据)附:注意调用的时候最好传控件的字符串,即lable.text等,否则会出现无法预知的bug。
另附:封装的代码,用类方法直接调用
.h文件
#import <Foundation/Foundation.h> @interface CalculateSize : NSObject + (CGSize)sizeForNoticeTitle:(NSString*)text font:(UIFont*)font maxW:(CGFloat)maxW; @end
.m实现
#import "CalculateSize.h" @implementation CalculateSize + (CGSize)sizeForNoticeTitle:(NSString*)text font:(UIFont*)font maxW:(CGFloat)maxW{ // CGRect screen = [UIScreen mainScreen].bounds; // CGFloat maxWidth = screen.size.width; CGSize maxSize = CGSizeMake(maxW, MAXFLOAT); CGSize textSize = CGSizeZero; // iOS7以后使用boundingRectWithSize,之前使用sizeWithFont if ([text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) { // 多行必需使用NSStringDrawingUsesLineFragmentOrigin,网上有人说不是用NSStringDrawingUsesFontLeading计算结果不对 NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading; NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init]; [style setLineBreakMode:NSLineBreakByCharWrapping]; NSDictionary *attributes = @{ NSFontAttributeName : font, NSParagraphStyleAttributeName : style }; CGRect rect = [text boundingRectWithSize:maxSize options:opts attributes:attributes context:nil]; textSize = rect.size; } else{ textSize = [text sizeWithFont:font constrainedToSize:maxSize lineBreakMode:NSLineBreakByCharWrapping]; } return textSize; } @end