Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString sizeWithAttributes: Inaccuracy

I want to know the width of an NSString displayed on the screen in pixels. So I can fit an NSTextField its bounds to be exactly the length of the string itself. So I used IB's "Label" NSTextField and for those who don't know what I mean, I got a label with title "Label", font "Lucida Grande 13px", not selectable, not editable, regular size, no background and according to IB its width is 38px wide.

If I want to get its width programatically I use

[@"Label" sizeWithAttributes: [NSDictionary dictionaryWithObject: [NSFont fontWithName: @"Lucida Grande" size: 13] forKey: NSFontAttributeName]].width

Which will give me 33.293457 . So that's about 5 px of the real width..

like image 974
Jef Avatar asked Mar 13 '10 18:03

Jef


1 Answers

I believe what you are noticing is the difference between the frame of the control and it's layout frame. See Frame vs Layout Frame for a good explanation.

You are doing the right thing in computing the width. For a Label, there is no extra padding at the top or bottom of the control, which is why you saw no problems with the height of your control. However, on the left and right of the control, there are an additional three pixels. This can be verified by looking at the Frame and Layout of a Label control in IB.

So, the ~5 pixels you noticed is actually exactly 6. Once you take into account this padding, you should have no further trouble.

Unfortunately, there is no API to determine what the padding is for various controls (Push Buttons have an additional 6 pixels on each side). I would suggest filing a bug report at http://bugreport.apple.com - Apple does base what APIs they provide in part on the number of requests for them. While IB will tell you, you will need to code those values yourself. If they change in the next OS release, you will need to update your application.

like image 97
ericg Avatar answered Sep 29 '22 05:09

ericg