如何转换
CGSize labelHeighSize = [text sizeWithFont: [UIFont systemFontOfSize:16] constrainedToSize:maximumSize lineBreakMode:NSLineBreakByTruncatingTail];
到
CGSize labelHeighSize = [text boundingRectWithSize:maximumSize options: attributes: context:
答案 0 :(得分:2)
首先是方法:
- (CGRect) boundingRectWithSize:(CGSize)size
options:(NSStringDrawingOptions)options
attributes:(NSDictionary *)attributes
context:(NSStringDrawingContext *)context;
返回CGRect
而不是CGSize
,因此您需要使用CGRect
。
修改强> 根据苹果文档,请参阅here,它说
如果
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;