Pages

Saturday, July 3, 2010

Cocoa: How to create buttons without Interface Builder

In Cocoa application it is possible to create controls in the run-time. The application delegate class, automatically generated by Xcode, contains method -applicationDidFinishLaunching. This is a good place to create and initialize such user interface controls.
For example, the following code creates an NSButton object in the left-bottom corner of the application window:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{
NSRect frame = NSMakeRect(10, 40, 90, 40);
NSButton* pushButton = [[NSButton alloc] initWithFrame: frame];
pushButton.bezelStyle = NSRoundedBezelStyle;
[self.window.contentView addSubview: pushButton];

pushButton.target = self;
pushButton.action = @selector(buttonClicked:);

[pushButton release];
}

- (IBAction) buttonClicked: (id)sender
{
NSLog(@"Calling -buttonClicked: with sender: %@", sender);
}

Add method -(IBAction) buttonClicked: (id)sender to the header file of the application delegate, build and launch the application:




In the console you will see the logging message from the -buttonClicked each time you press on the button:

Loading program into debugger…
Program loaded.
run
[Switching to process 22626]
Running…
2010-07-03 10:52:13.424 ButtonWithoutIB[22626:a0f] Calling -buttonClicked: with sender:
2010-07-03 10:52:14.088 ButtonWithoutIB[22626:a0f] Calling -buttonClicked: with sender:
2010-07-03 10:52:15.088 ButtonWithoutIB[22626:a0f] Calling -buttonClicked: with sender:
2010-07-03 10:52:15.288 ButtonWithoutIB[22626:a0f] Calling -buttonClicked: with sender:


In case someone needs, it is possible to press on this button from the code too. Let's send -performClick message to our button from the code. Add this line before the button release:
[pushButton performClick:self];

Now the logging message appears in console when the application starts up:

Same way will work for NSPopUpButton:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{
NSRect frame = NSMakeRect(10, 40, 120, 40);
NSPopUpButton* popUpButton = [[NSPopUpButton alloc] initWithFrame:frame];
[self.window.contentView addSubview:popUpButton];

[popUpButton addItemWithTitle: @"First"];
[popUpButton addItemWithTitle: @"Second"];
[popUpButton addItemWithTitle: @"Third"];

NSLog( @"popUpButton itemArray: %@", popUpButton.itemArray );
NSLog( @"popUpButton itemTitles: %@", popUpButton.itemTitles );

popUpButton.target = self;
popUpButton.action = @selector( itemDidChange: );

[popUpButton release];
}

- (IBAction)itemDidChange:(id)sender
{
NSLog( @"selected item: %@", [sender selectedItem] );
NSLog( @"selected index: %i", [sender indexOfSelectedItem] );
NSLog( @"selected title: %@", [sender titleOfSelectedItem] );
}

The source code in this article is from the nice book about Cocoa: "Cocoa and Objective-C Up and Running".

No comments:

Post a Comment