Is there a way to programmatically determine the correct sizes for Apple's built-in controls?

When writing Cocoa applications, I do most of the layout of the user interface programmatically. For instance:

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

My question is about kDefaultPopUpButtonHeight constant. I currently maintain a source file full of such constants, and I manually fill in the required sizes. I can determine the correct sizes by dropping the new control into an empty 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 that each NSControl should have a class method something like this: +(NSSize)defaultSize or for controls like NSButton , which have different default sizes depending on the particular button style, something like +(NSSize)defaultSizeForButtonStyle:(NSButtonStyle)buttonStyle .

The Apple Human Interface Guidelines contain information about the layout of the controls and the distance between the controls, but it doesn't say anything about the correct sizes for the individual controls.

+2
source share
1 answer

I agree with Peter and recommend you use Interface Builder. But if that doesn't suit your situation, here is one way to find the best size for most controls:

 NSSize idealSize = [[control cell] cellSize]; 

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

In addition, cellSize really gives you the minimum size for a control, not necessarily the best size. For example, for a Cocoa aqua style button with the text "OK", it will return a width that will be narrower than recommended by HIG. For your purposes, it sounds like you are only interested in a fixed height. - [NSCell cellSize] should work fine.

+1
source

All Articles