Search code examples
iosxcodecocoa-touchios7

Lost with the replacement for deprecated sizeWithFont: in iOS 7


I have a warning that sizeWithFont: is deprecated, i have try to replace it to sizeWithAttributes: but everything i try is not working.

The code is supposed to tell me the expected size of a UILabel and the cCell is the cell and the label fro the IB.

Thanks for all your help.

CGSize maximumLabelSize = CGSizeMake(210, FLT_MAX);

expectedLabelSize = [labelText sizeWithFont:cCell.lblHotelResponse.font constrainedToSize:maximumLabelSize lineBreakMode:cCell.lblHotelResponse.lineBreakMode];

Solution

  • You need to use sizeWithAttributes: instead.

    NSDictionary *attributeDict = @{NSFontAttributeName:cCell.lblHotelResponse.font};
    CGSize expectedLabelSize    = [labelText sizeWithAttributes:attributeDict];
    

    Another way is:

    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:labelText attributes:@{NSFontAttributeName: cCell.lblHotelResponse.font}];
    CGRect rect                          = [attributedString boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    CGSize labelSize                     = rect.size;
    

    References:

    1. sizeWithAttributes:
    2. boundingRectWithSize:options:attributes: