PDA

View Full Version : Dynamically creating forms-need help




xyzeugene
Feb 16, 2009, 07:39 PM
Hello,

Does anyone know how to dynamicallyI(not static) create a cocoa form? Like a window with a button and a label that changes with the button? I can do this in Delphi - I'm curious how to do it in Cocoa.

Thanks

Eugene



kainjow
Feb 16, 2009, 09:59 PM
Here's some basic code for creating a window and adding a button to it that beeps when clicked. Not as fun as drag and drop, eh? :)

- (void)buttonAction:(id)sender
{
NSBeep();
}

- (void)createWindow
{
// create a window
NSRect contentRect = NSMakeRect(0.0, 0.0, 250.0, 150.0);
NSUInteger style = NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask;
NSWindow *window = [[NSWindow alloc] initWithContentRect:contentRect styleMask:style backing:NSBackingStoreBuffered defer:YES];
[window setTitle:@"Window"];

// get the window's content view, where everything goes
NSView *contentView = [window contentView];
NSRect bounds = [contentView bounds];

// create a button
CGFloat width = 120.0, height = 32.0;
NSRect buttonRect = NSMakeRect(floor((NSWidth(bounds) - width)/2), floor((NSHeight(bounds)-height)/2), width, height);
NSButton *button = [[NSButton alloc] initWithFrame:buttonRect];
[button setAutoresizingMask:NSViewMinXMargin | NSViewMaxXMargin | NSViewMinYMargin | NSViewMaxYMargin];
[button setButtonType:NSMomentaryLightButton];
[button setBezelStyle:NSRoundedBezelStyle];
[button setFont:[NSFont systemFontOfSize:13.0]];
[button setTitle:NSLocalizedString(@"Hello World", nil)];
[button setTarget:self];
[button setAction:@selector(buttonAction:)];

// add the button to the window
[contentView addSubview:button];
[button release];

// center and open the window
[window center];
[window makeKeyAndOrderFront:nil];
}

xyzeugene
Feb 17, 2009, 10:38 AM
Kainjow
This is exactly what I need - clean implementation too!!! I alot of my gui design like this when I am programming in Delphi. Extremely useful code.

Thanks Again

Eugene