Contenting deprecated sizeWithFont:constrainedToSize to boundingRectWithSize:options:attributes:context:

允我心安 提交于 2019-12-02 18:57:59

问题


How can I convert

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

to

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

回答1:


First of all the method:

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

returns CGRect not the CGSize so you need to use CGRect.

EDIT according to apple docs see here, it says

This option is ignored if NSStringDrawingUsesLineFragmentOrigin is not also set. In addition, the line break mode must be either NSLineBreakByWordWrapping or NSLineBreakByCharWrapping for this option to take effect. The line break mode can be specified in a paragraph style passed in the attributes dictionary argument of the drawing methods.

Below is the sample code that you can use:

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; 


来源:https://stackoverflow.com/questions/23075693/contenting-deprecated-sizewithfontconstrainedtosize-to-boundingrectwithsizeopt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!