简体   繁体   中英

Adding an instance of NSButton to NSWindow programmatically

I am in the early stages of learning programming/Cocoa and I decided I want to create a simple UI programmatically so as to better visualize the relationship between code/GUI. I opened up the default template for Cocoa in OS X. My only modifications to the template so far are:

@property NSButton *theButton;

In Appdelegate.h and

- (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];
    

}

In Appdelegate.m.

However I am getting the error:

[self.window addSubview:self.theButton];

No visible @interface for 'NSWindow' declares the selector 'addSubview:'

Why is this?

NSWindow inherits from NSResponder so you can use like

[self.window.contentView addSubview: yourbutton];

But for UIWindow you can use. [self.window addSubview:button] because it inherits from UIView. Hope it will more clear...

Because NSWindow doesn't have an addSubview: method. That method is part of NSView. You might want the window's contentView.

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