views:

149

answers:

1

When writing Cocoa apps, I do the majority of the user interface layout programmatically. For example:

NSRect popUpFrame = NSMakeRect(10, 10, 100, kDefaultPopUpButtonHeight);
NSPopUpButton * popUp = [[NSPopUpButton alloc] initWithFrame:popUpFrame];
//...

My question is about that kDefaultPopUpButtonHeight constant. I currently maintain a source file full of such constants, and I fill in the proper sizes manually. I am able to determine the correct sizes by dropping a new control into a blank view in Interface Builder and then checking its properties to see what size IB gives it.

There must be a better way. Is it possible to access these values at runtime? Ideally, I would expect every NSControl to have a class method something like: +(NSSize)defaultSize, or, for controls like NSButton that have different default sizes depending on the particular button style used, something like +(NSSize)defaultSizeForButtonStyle:(NSButtonStyle)buttonStyle.

Apple's Human Interface Guidelines has information about control layout and the spacing between controls, but it doesn't say anything about the proper sizes for individual controls.

+1  A: 

I agree with Peter, and would recomend that you use Interface Builder. But if that isn't appropriate in your situation, here's one way to find the best size for most controls:

NSSize idealSize = [[control cell] cellSize];

If you need more control over the sizing, you can use the -[NSCell cellSizeForBounds:] method.

Also, cellSize really gives you the minimum size for a control, not necessarily the best size. For example, for a Cocoa aqua style push button with the text "OK", it would return a width that more narrow than the HIG would recommend. For your purposes, it sounds like you're only interested in the fixed hight portion of the size. -[NSCell cellSize] should work great.

Jon Hess
Sorry it took so long to mark this as accepted. I haven't had a chance to test it out until now, but cellSize is exactly what I was looking for. Thank you!
e.James