Dynamically creating forms-need help

Discussion in 'Mac Programming' started by xyzeugene, Feb 16, 2009.

  1. macrumors newbie

    Joined:
    Feb 13, 2009
    #1
    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
     
  2. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    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];
    }
     
  3. thread starter macrumors newbie

    Joined:
    Feb 13, 2009
    #3
    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
     

Share This Page