首先方法:
- (CGRect) boundingRectWithSize:(CGSize)size
options:(NSStringDrawingOptions)options
attributes:(NSDictionary *)attributes
context:(NSStringDrawingContext *)context;
返回CGRect
不是CGSize
所以你需要使用CGRect
.
根据苹果文档进行编辑,请参见此处,它说
NSStringDrawingUsesLineFragmentOrigin
如果未同时设置,则忽略此选项。另外,换行模式必须是
NSLineBreakByWordWrapping
或NSLineBreakByCharWrapping
才能使该选项生效。可以在绘图方法的属性字典参数中传递的段落样式中指定换行模式。
以下是您可以使用的示例代码:
NSString *text = @"Some text to measure";
UIFont *labelFont = [UIFont systemFontOfSize:16];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
//set the line break mode
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attrDict = [NSDictionary dictionaryWithObjectsAndKeys:labelFont,
NSFontAttributeName,
paragraphStyle,
NSParagraphStyleAttributeName,
nil];
//assume your maximumSize contains {255, MAXFLOAT}
CGRect lblRect = [text boundingRectWithSize:(CGSize){225, MAXFLOAT}
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attrDict
context:nil];
CGSize labelHeighSize = lblRect.size;