内容弃用的sizeWithFont:constrainedToSize到boundingRectWithSize:options:attributes:context:

时间:2014-04-15 05:57:24

标签: ios objective-c deprecation-warning

如何转换

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

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

1 个答案:

答案 0 :(得分:2)

首先是方法:

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

返回CGRect而不是CGSize,因此您需要使用CGRect

修改 根据苹果文档,请参阅here,它说

  

如果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;