在 Objective-c Cocoa 中添加运行时按钮控制
如果我将这些行放入 xxxAppDelegate.m 文件中,它就可以正常工作。但我需要在另一个模块下使用它,例如在 main.m 等中。编译器生成一个错误,指出窗口未定义。 “window”是在xxxAppDelegate模块中定义的,如何在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:)];
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:)];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Cocoa 喜欢保持模块化。 window 不存在于委托的上下文中,因为它是另一个类。
如果应用程序委托中的
window
不存在,则为它创建一个属性:.h
.m
然后:
((YourDelegateClass *)[NSApp delegate]).window
应该可以工作。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
.m
then:
((YourDelegateClass *)[NSApp delegate]).window
should work.您可以将该代码粘贴到任何需要的地方(即,将其放在 main 中)。除非,是否有某种原因需要在委托中声明它?
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?