0

我怎样才能转换

 CGSize labelHeighSize = [text sizeWithFont: [UIFont systemFontOfSize:16] constrainedToSize:maximumSize lineBreakMode:NSLineBreakByTruncatingTail];

CGSize labelHeighSize = [text boundingRectWithSize:maximumSize options:  attributes:  context: 
4

1 回答 1

2

首先方法:

 - (CGRect)   boundingRectWithSize:(CGSize)size 
                           options:(NSStringDrawingOptions)options 
                        attributes:(NSDictionary *)attributes 
                           context:(NSStringDrawingContext *)context;

返回CGRect不是CGSize所以你需要使用CGRect.

根据苹果文档进行编辑,请参见此处,它说

NSStringDrawingUsesLineFragmentOrigin如果未同时设置,则忽略此选项。另外,换行模式必须是 NSLineBreakByWordWrappingNSLineBreakByCharWrapping才能使该选项生效。可以在绘图方法的属性字典参数中传递的段落样式中指定换行模式。

以下是您可以使用的示例代码:

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; 
于 2014-04-15T06:30:16.197 回答