简体   繁体   中英

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM