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

xyzeugene

macrumors newbie
Original poster
Feb 13, 2009
25
0
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

Moderator emeritus
Jun 15, 2000
7,958
7
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? :)

Code:
- (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

macrumors newbie
Original poster
Feb 13, 2009
25
0
Thanks

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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.