tags:

views:

118

answers:

1

Is this possible to get the coordinates of where the text drawn in standard (not custom) Cocoa controls? Actually, I need a baseline of the text, the y-axis offset value (relative to the y-origin of the view’s frame rectangle). This is what the Interface Builder shows on design pane when Layout->Show Layout Rectangles selected.

+2  A: 

Unfortunately, there isn't a single solution that works for all controls and cells. You should be able to get a good approximation of this information with these methods:

-[NSCell titleRectForBounds:]
-[NSCell font]
-[NSFont ascender]

Here's some code that works for NSButton/NSButtonCell

NSRect titleRect = [[button cell] titleRectForBounds:[button bounds]];
CGFloat baseline = ceil(NSMinY(titleRect) + [[[button cell] font] ascender]);

At this point, baseline is in the button's (bounds) coordinate space. You might want to convert it to some other space with -[NSView convertPoint:toView:];

Also, that "ceil" in there is an approximation. Not all controls will do that. Some might floor, or use some other rounding function. Or they might layout their title's completely differently, and this approximation won't work.

Jon Hess
This can be a real pain to get right. In Adobe Lightroom we have our own layout system for controls. One tool that was a real boon to verifying where the baseline for the text was drawing was to add some debugging code by using poseAs: and inserting some global drawing code to overlay over the normal drawing. Essentially we can turn this on in debug builds to show where the baseline is on all the controls we care about. If you are doing a lot of this it can end up saving you time.I cannot share any code due to the proprietary nature, sorry.
Jon Steinmetz
poseAs: was deprecated in Leopard ;)
IlDan