Programmatically creating GUI's in Cocoa?

Discussion in 'Mac Programming' started by rezeda, Nov 11, 2008.

  1. rezeda macrumors newbie

    Nov 11, 2008
    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!
  2. robbieduncan Moderator emeritus


    Jul 24, 2002
    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...
  3. liptonlover macrumors 6502a

    Mar 13, 2008
    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.
  4. pilotError macrumors 68020


    Apr 12, 2006
    Long Island
    Take a look at the GNUStep tutorials. They do a pretty good job at basic interface building through the API.
  5. chaithrika macrumors newbie

    Nov 24, 2008
    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

    @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 ];


Share This Page