以编程方式将 NSButton 实例添加到 NSWindow

Pop*_*nel 0 macos cocoa objective-c

我正处于学习编程/Cocoa 的早期阶段,我决定以编程方式创建一个简单的 UI,以便更好地可视化代码/GUI 之间的关系。我在 OS X 中打开了 Cocoa 的默认模板。到目前为止,我对模板的唯一修改是:

@property NSButton *theButton;
Run Code Online (Sandbox Code Playgroud)

在 Appdelegate.h 和

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    CGRect buttonFrame;

    buttonFrame = CGRectMake(20, 20, 15, 5);
    self.theButton = [[NSButton alloc]initWithFrame:buttonFrame];
    [self.theButton setTitle:@"test"];
    [self.window addSubview:self.theButton];
    

}
Run Code Online (Sandbox Code Playgroud)

在 Appdelegate.m 中。

但是我收到错误:

[self.window addSubview:self.theButton];

'NSWindow' 没有可见的 @interface 声明选择器 'addSubview:'

为什么是这样?

小智 5

NSWindow 继承自 NSResponder 所以你可以使用像

[self.window.contentView addSubview: yourbutton];

但对于 UIWindow 你可以使用。[self.window addSubview:button]因为它继承自UIView。希望能更清楚一点...