Nirav Nirav - 6 months ago 60
Objective-C Question

sizeWithFont method is deprecated. boundingRectWithSize returns an unexpected value

In iOS7,

sizeWithFont
is deprecated, so I am using
boundingRectWithSize
(which returns a CGRect value). My code:

UIFont *fontText = [UIFont fontWithName:[AppHandlers zHandler].fontName size:16];
// you can use your font.

CGSize maximumLabelSize = CGSizeMake(310, 9999);

CGRect textRect = [myString boundingRectWithSize:maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:fontText}
context:nil];

expectedLabelSize = CGSizeMake(textRect.size.width, textRect.size.height);


In
textRect
, I'm getting a size greater than my
maximumLabelSize
, a different size than when using
sizeWithFont
. How can I resolve this issue?

Answer

How about create new label and using sizeThatFit:(CGSize)size ??

UILabel *gettingSizeLabel = [[UILabel alloc] init];
gettingSizeLabel.font = [UIFont fontWithName:@"YOUR FONT's NAME" size:16];
gettingSizeLabel.text = @"YOUR LABEL's TEXT";
gettingSizeLabel.numberOfLines = 0;
gettingSizeLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(310, CGFLOAT_MAX);

CGSize expectSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];

Edit: This upper code is not good for ios 7 and above, so please use below:

CGRect textRect = [myString boundingRectWithSize:maximumLabelSize   
                         options:NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesFontLeading
                         attributes:@{NSFontAttributeName:fontText}
                         context:nil];