6

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?

Heiko
  • 191
  • 1
  • 5
  • Maybe this link should help you http://stackoverflow.com/questions/19028743/ios7-uitextview-contentsize-height-alternative/19067476#19067476 – rajdurai Jan 16 '14 at 09:41

2 Answers2

7

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.

Nirav Jain
  • 5,088
  • 5
  • 40
  • 61
1

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}
muffe
  • 2,285
  • 1
  • 19
  • 23
  • This is also in the function-documentation: In iOS 7 and later, this method returns fractional sizes (in the size component of the returned CGRect); to use a returned size to size views, you must use raise its value to the nearest higher integer using the ceil function. But: In iOS 6 i got e.g. 18 and with iOS 7 i get 16.799999 - so a ceil() gives me 17. And this is just for a single line of text, with multiline text it gets even worse. – Heiko Sep 27 '13 at 13:34