views:

1328

answers:

2

According to Cocoa Programming for Mac OS X, 3rd Edition, on page 245 (chapter 17), you will usually create views in Interface Builder. However, it is possible to create them in code, a la:

NSView *superview = [window contentView]; 
NSRect frame = NSMakeRect(10, 10, 200, 100); 
NSButton *button = [[NSButton alloc] initWithFrame:frame]; 
[button setTitle:@"Click me!"]; 
[superview addSubview:button]; 
[button release];

That’s all well and good, but how would I wire up said control’s outlets to actions in code? (In .NET, this is an easy thing; add a delegate ... I’m hoping it’s similarly easy in Cocoa/Obj-C.)

+9  A: 

You can wire them up using a simple assignment. To continue your code from above:

[button setTarget: self];
[button setAction: @selector(myButtonWasHit:)];

Ben Gottlieb
Beautiful, thanks! That's actually easier than it is in .NET.
John Rudy
+5  A: 

And if you want to target the first responder rather than a particular object:

[button setTarget:nil];
[button setAction:@selector(myAction:)];
Mike Abdullah