I'm creating a class that displays a window with some text, a "Don't show again" checkbox and a button. In order to be reusable, the class resizes the window as needed to fit the text.
However, there is some slight imprecision in the calculations - if I don't add 5 pixels to the width some strings are truncated. (The last word is simply removed.)
Here's what I have:
// NSTextField *textLabel;
// NSString *text;
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject: [textLabel font] forKey: NSFontAttributeName];
NSRect textFrame = [text boundingRectWithSize:NSMakeSize(textLabel.frame.size.width, (unsigned int)-1)
options:(NSStringDrawingDisableScreenFontSubstitution | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:stringAttributes];
textFrame.size.width += 5;
I temporarily set the label's background color to yellow to make the debugging easier, and it clearly expands to almost fit that last word. 4 pixels extra is enough on that test string.
Do note that not all strings fail without these added pixels.
There are two reasons that I care:
1) I want to learn why it's slightly wrong, and more importantly
2) I'm figuring that by changing the width after the calculation, the wrapping can theoretically change and leave the otherwise last line unused, creating extra empty space below the text.