Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a launch NSWindow in Cocoa on a button click

Tags:

cocoa

I have an NSWindow that I defined in interface builder. I want to make it so that when the user clicks a button, it opens a new instance that NSWindow. Do I have to subclass NSWindow or something?

like image 893
Sam Lee Avatar asked Nov 29 '22 00:11

Sam Lee


1 Answers

If you created the window in IB and it's in your main nib file, you cannot create a "new instance" each time you press a button. When you create an object in the nib file, an instance is actually created by IB and then archived into the nib file, so you get that instance. Assuming your window is wired to a variable named auxWindow on the same object that responds to your button click, and the action message is named buttonClick, you could do something like this to show it:

-(IBAction)buttonClick:(id)sender {
    if(! [auxWindow isVisible] )
        [auxWindow makeKeyAndOrderFront:sender];
}

This will cause the aux window that you defined in IB to appear on the screen and become the key window (and foremost window in the application). Please note, however, that if you intend to reuse this window, you must uncheck the box in the IB Inspector that says Release on Close, otherwise you will get an access violation the next time you click the button.

This is a simple answer to your basic question, but window programming can be quite complicated and is usually very specific (for instance, do you really want a panel for what you're doing?)... so I strongly suggest that you read the Window Programming Guide for more information on this topic, and then ask very specific questions here when you get stuck.

like image 148
Jason Coco Avatar answered May 25 '23 13:05

Jason Coco