How to close a window programmatically in Cocoa Mac?
17,611
Solution 1
Apple has some useful sample code on Nib Loading. It doesn't directly address this question however; the following code does.
@interface CloseWindowAppDelegate : NSObject <NSApplicationDelegate> {
NSWindow *window;
IBOutlet NSWindow * secondWindow;
NSNib * secondNib;
}
@property (assign) IBOutlet NSWindow *window;
- (IBAction)openSecondWindow:(id)sender;
- (IBAction)closeSecondWindow:(id)sender;
@end
#import "CloseWindowAppDelegate.h"
@implementation CloseWindowAppDelegate
@synthesize window;
- (IBAction)openSecondWindow:(id)sender {
secondNib = [[NSNib alloc] initWithNibNamed:@"SecondWindow" bundle:nil];
[secondNib instantiateNibWithOwner:self topLevelObjects:nil];
[secondWindow makeKeyAndOrderFront:nil];
}
- (IBAction)closeSecondWindow:(id)sender {
[secondWindow close];
[secondNib release];
}
@end
Solution 2
I was looking for this for ages! A simple
[self close];
[self release];
worked for me. :-)
Solution 3
This is for someone who is using Swift
and NSStoryBoardSegue
, here is the same way to achieve it
NSApplication.sharedApplication().mainWindow?.close() // close current window first
self.performSegueWithIdentifier("id_of_your_segue", sender: self) // open the second view by invoking the segue that is set to connect two views.
Related videos on Youtube
Author by
ShinuShajahan
iPhone/iPad application developer Twitter Page-> http://www.twitter.com/ShinuShajahan Facebook Page-> http://www.facebook.com/ShinuShajahan Blog-> http://www.essenzeoflife.blogspot.com
Updated on June 04, 2022Comments
-
ShinuShajahan almost 2 years
How can I programmatically close a window in cocoa mac ? I have opened a second window/xib from the first window/xib using button click. I need to close the first window/xib programmatically on opening or clicking the button. How can I do that?
-
ShinuShajahan about 13 years> well explained code. Found very useful. New to stackoverflow and pretty much impressed. Here people like you are explaining very well. Thanks. :)
-
ShinuShajahan about 13 years@Josh-> it worked well. thank you. Your code found useful regarding the problem I was facing. :)