Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAttributedString boundingRectWithSize gives different heights between iOS 6 and iOS 7

Recently updated my App to iOS 7 using XCode 5 and found that boundingRectWithSize gives different heights (in the size part) calculating the bounds of attributed Strings.

The following line gives me different Results between iOS 6 and iOS 7:

CGRect rect = [self boundingRectWithSize:CGSizeMake(inWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];

"self" is an NSAttributedString and "inWidth" is the maximum width in pixels the string should fit in.

I think thats because iOS 7 has a different font handling than iOS 6.

Anyone got a working solution to calculate the height of a string on both iOS versions?

like image 648
Heiko Avatar asked Sep 27 '13 09:09

Heiko


2 Answers

As we cant use sizeWithAttributes for all iOS greater than 4.3 we have to write conditional code for 7.0 and previous iOS. So I suggest to use given solution

UILabel *gettingSizeLabel = [[UILabel alloc] init];
gettingSizeLabel.font = [UIFont fontWithName:[AppHandlers zHandler].fontName size:16];
gettingSizeLabel.text = @"YOUR TEXT HERE";
gettingSizeLabel.numberOfLines = 0;
CGSize maximumLabelSize = CGSizeMake(310, 9999); // this width will be as per your requirement

CGSize expectedSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];

The option is quite well and working smoothly in all iOS without conditional code.

like image 87
Nirav Jain Avatar answered Oct 14 '22 19:10

Nirav Jain


I had the same problem, for me a simple ceil() on the height solved it. Also be sure to set the right attributes for youre attributed string e.g.

@{NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName : label.font}
like image 1
muffe Avatar answered Oct 14 '22 20:10

muffe