Adding button control at running time in objective-c Cocoa
If I put these lines in the xxxAppDelegate.m file, it works fine. But I need to use it under another module开发者_开发百科 such as in main.m etc. The compiler generated an error stated that window is undefined. "window" is defined in the xxxAppDelegate modues, how do you reference it in another modules beside xxxAppDelegate.m
NSView *superview = [window contentView];
NSButton *button = [ [ NSButton alloc ] initWithFrame: NSMakeRect( 10.0, 10.0, 200.0, 100.0 ) ];
[ button setBezelStyle:NSRoundedBezelStyle];
[ button setTitle: @"Click" ];
[superview addSubview:button];
[button setTarget:self];
[ button setAction:@selector(doSomething:)];
Cocoa likes to keep things modular. window doesn't exist in the context of the delegate, because it is another class.
make a property for window
in your app delegate if it doesn't exist:
.h
@property(readonly)NSWindow * window;
.m
@synthesize window;
then:
((YourDelegateClass *)[NSApp delegate]).window
should work.
You could just paste that code wherever you need it (IE, put it in main). Unless, is there some reason you need it declared in the delegate?
精彩评论