How to close a window programmatically in Cocoa Mac?

帅比萌擦擦* 提交于 2019-12-20 10:41:32

问题


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?


回答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



回答2:


I was looking for this for ages! A simple

[self close];
[self release];

worked for me. :-)




回答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.



回答4:


U may use "performClose" action. Choose nib file (your window which u wont closed), open Connections inspector, connect "performClose" action with u button.



来源:https://stackoverflow.com/questions/5591618/how-to-close-a-window-programmatically-in-cocoa-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!