Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Creating Controls in Cocoa

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.)

like image 675
John Rudy Avatar asked Dec 08 '08 15:12

John Rudy


1 Answers

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

[button setTarget: self];
[button setAction: @selector(myButtonWasHit:)];
like image 175
Ben Gottlieb Avatar answered Sep 20 '22 20:09

Ben Gottlieb