Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

rezeda

macrumors newbie
Original poster
Nov 11, 2008
10
0
I cannot find a single example of how to add few buttons programmatically to a window (that is, not using the interface builder). Although it might seem crazy not to use the builder since it was designed to do that, my application needs controls to be added dynamically, so the number of the controls, the positions and the sizes are not known before.
Anybody else has this problem? Any help is appreciated!
 

robbieduncan

Moderator emeritus
Jul 24, 2002
25,611
893
Harrogate
Not too difficult. In general you can create a new control by calling alloc/initWithFrame:. Then simply call addSubview: on the view you want to add it to. Of course you may well need to do some more setup (set the label on a button for example), but that's the general idea...
 

liptonlover

macrumors 6502a
Mar 13, 2008
989
0
If you know basic programming, then all you need is the GUI item's class. Go to it's class and go through the methods that you need to set various attributes, (there are quite a few even for just a button) such as label, size, location, style, color, etc.. I've done it a few times, it gets easy after a while.

And don't forget what robbie said too. Super classes are important as well.
 

chaithrika

macrumors newbie
Nov 24, 2008
7
0
Create NSWindow programatically in Cocoa

I hope this helps. :apple:

In file main.m:

int main(int argc, char *argv[])
{
WindowController *windowController = [ [ WindowController alloc ] init ];
return NSApplicationMain(argc, (const char **) argv);
}

In file WindowController.mm:

@implementation WindowController

- (id) init
{
self = [ super init ];
if( !self )
return nil;

[ NSBundle loadNibNamed: @"MainMenu" owner: self ];
return self;
}

- (void) awakeFromNib
{
NSRect windowRect = NSMakeRect( 200.0, 200.0, 400.0, 300.0 );

NSWindow *window = [ [ NSWindow alloc ] initWithContentRect:windowRect styleMask:( NSResizableWindowMask | NSClosableWindowMask | NSTitledWindowMask) backing:NSBackingStoreBuffered defer:NO];

NSButton *button = [ [ NSButton alloc ] initWithFrame: NSMakeRect( 300.0, 20.0, 80.0, 50.0 ) ];

[ button setBezelStyle:NSRoundedBezelStyle];
[ button setTitle: @"Click" ];
[ [ window contentView ] addSubview: button ];
[window makeKeyAndOrderFront:nil];
}

- (void)dealloc
{
[ super dealloc ];
}

@end
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.