macos 如何在 Cocoa Mac 中以编程方式关闭窗口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5591618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 07:55:41  来源:igfitidea点击:

How to close a window programmatically in Cocoa Mac?

objective-ccocoamacoswindowxib

提问by ShinuShajahan

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?

如何以编程方式关闭 cocoa mac 中的窗口?我使用按钮单击从第一个窗口/xib 打开了第二个窗口/xib。我需要在打开或单击按钮时以编程方式关闭第一个窗口/xib。我怎样才能做到这一点?

回答by jscs

Apple has some useful sample code on Nib Loading. It doesn't directly address this question however; the following code does.

Apple 在Nib Loading上有一些有用的示例代码。然而,它并没有直接解决这个问题;下面的代码可以。

@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

回答by October

I was looking for this for ages! A simple

我一直在寻找这个!一个简单的

[self close];
[self release];

worked for me. :-)

对我来说有效。:-)

回答by Telvin Nguyen

This is for someone who is using Swiftand NSStoryBoardSegue, here is the same way to achieve it

这适用于正在使用Swiftand 的人NSStoryBoardSegue,这是实现它的相同方法

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.

回答by Nikolai Nagornyi

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

你可以使用“performClose”动作。选择 nib 文件(您不会关闭的窗口),打开连接检查器,使用 u 按钮连接“performClose”操作。