我怎样才能在Cocoa Mac中编程关闭一个窗口?我通过按钮点击从第一个窗口/xib打开了第二个窗口/xib。我需要在打开或点击按钮时程序化地关闭第一个窗口/xib,我应该怎么做?
可以使用以下代码行来关闭第一个窗口:
``` let window = NSApplication.shared.windows.first window?.close() ```我怎样才能在Cocoa Mac中编程关闭一个窗口?我通过按钮点击从第一个窗口/xib打开了第二个窗口/xib。我需要在打开或点击按钮时程序化地关闭第一个窗口/xib,我应该怎么做?
可以使用以下代码行来关闭第一个窗口:
``` let window = NSApplication.shared.windows.first window?.close() ```在Nib加载的页面上,苹果提供了一些有用的示例代码。不过,它并没有直接回答这个问题;下面的代码则可以。
@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
[self close];
[self release];
Swift
和 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.
firstView
听起来像是一个NSView
的名称,而不是NSWindow
。如果它确实是一个NSWindow
,那么它将会响应[window orderOut:nil]
(这里的:nil
非常重要)。 - dreamlax