如何在 OS X 故事板开始时隐藏初始 window

How to hide the initial window on start with OS X storyboards

我正在创建一个 OS X 状态栏应用程序,因此 我希望该应用程序以隐藏方式启动

我创建了一个 "storyboard" 应用程序,初始 window 总是显示,即使 "Visible at launch" 未选中(默认情况下未选中)。


注意:如果我禁用“Is initial controller”,那么应用程序会在没有任何 window 的情况下正确启动,但我的(现在是孤儿)window 似乎永远不会添加到情节提要中:

var mainWindow = NSStoryboard(name: "Main", bundle: nil)?.instantiateControllerWithIdentifier("mainWindow")

找不到 "mainWindow" 控制器(即使我在 Window 控制器上正确设置了 "Storyboard ID")。

所以我认为最好保留“Is initial controller”,而只是将主要 window 隐藏在开始处...

这可能有点乱七八糟,但你可以做到这一点

func applicationDidFinishLaunching(notification: NSNotification) {
    // Insert code here to initialize your application
    NSApplication.sharedApplication().windows.last!.close()
}

然后……

NSApplication.sharedApplication().windows.last!.makeKeyAndOrderFront(nil)
NSApplication.sharedApplication().activateIgnoringOtherApps(true)

取消选中 Storyboard 上的 "Is Initial Controller" 框,让您的应用程序没有初始控制器。您的应用将 运行,但不会 window。

取消选中 "Is Initial Controller",但随后您需要手动设置故事板及其关联 NSWindowController

显示了执行此操作的精确方法 in this answer,我将在此处引用:

[...] in your AppDelegate, set up a property for the window controller:

@property NSWindowController *myController;

In your applicationDidFinishLaunching: method implementation, create a reference to the Storyboard. This way you get access your window controller from the storyboard. After that, the only thing left to do is to display the window by sending your window controller the showWindow: method.

#import "AppDelegate.h"

@interface AppDelegate ()
@end

@implementation AppDelegate

@synthesize myController;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // get a reference to the storyboard
    NSStoryboard *storyBoard = [NSStoryboard storyboardWithName:@"Main" bundle:nil]; 
    // instantiate your window controller 
    myController = [storyBoard instantiateControllerWithIdentifier:@"secondWindowController"];
    // show the window
    [myController showWindow:self];
}

@end

方法和你试过的一样:

let storyboard = NSStoryboard(name: "Main", bundle: nil)
guard let mainWC = storyboard.instantiateControllerWithIdentifier("MainWindowController") as? MainWindowController else {
   fatalError("Error getting main window controller")
}
// optionally store the reference here
self.mainWindowController = mainWC

mainWC.window?.makeKeyAndOrderFront(nil) // or use `.showWindow(self)`

您可能唯一忘记的是取消选中"Release when closed"。 这将立即释放 window 并防止故事板加载机制找到它,即使您有正确的标识符也是如此。