0

How can I use boundingRectWithSize:options:attributes:context: to return exactly the same size than intrinsicContentSize of a UILabel?

For example, if I use it like below, I get differences of up to 1 pixel:

const CGSize maxSize = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
NSDictionary * attributes = @{NSFontAttributeName:self.font};
CGSize textSize = [label.text boundingRectWithSize:maxSize
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                        attributes:attributes
                                           context:nil].size;
NSLog(@"1: %@", NSStringFromCGSize(label.intrinsicContentSize));
NSLog(@"2: %@", NSStringFromCGSize(textSize));

E.g:

1: {53, 17}
2: {52.122002, 18}

The documentation of boundingRectWithSize says:

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.

So the difference between 53 and 52.122002 makes sense and can be dealt with by using ceil. However, the 1-pixel height difference can't.

Should I be using something else entirely?

hpique
  • 119,096
  • 131
  • 338
  • 476

0 Answers0