sizeWithAttributes gets me a different CGSize width and height

519 Views Asked by At

In iOS 7 sizeWithFont: is deprecated. The suggested replacement method is sizeWithAttributes:
But when I change the method from sizeWithFont: to sizeWithAttributes:
I get different Values.

Here my Code:

CGSize temp = [opt.option sizeWithFont:[UIFont fontWithName:fontFamily size:[self randomFontSize]]];
NSLog(@"Old SizeWithFont value %f x %f",temp.height, temp.width);

NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:fontFamily size:[self randomFontSize]]};
temp = [opt.option sizeWithAttributes: attributes];
NSLog(@"New SizeWithAttribute has value %f x %f",temp.height, temp.width);

And the output is :

linespacing 16.33, fontsize 16.00
Old SizeWithFont value 18.000000 x 47.000000
New SizeWithAttribute has value 17.875000 x 46.250000

Do I'm doing something wrong ? I

1

There are 1 best solutions below

1
danh On BEST ANSWER

The attributed text method description implies a behavior difference (boldface added by me)...

This method returns fractional sizes; to use a returned size to size views, you must raise its value to the nearest higher integer using the ceil function.

It also states that integral sizes should be computed with ceil() (in other words round-up). Doing so makes your experiment work as expected...

NSLog(@"New SizeWithAttribute has value %f x %f",ceil(temp.height), ceil(temp.width));