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

前端 未结 1 1804
北恋
北恋 2021-01-27 16:34

How can I convert

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


        
相关标签:
1条回答
  • 2021-01-27 17:26

    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; 
    
    0 讨论(0)
提交回复
热议问题