问题
The best I have been able to figure out is:
func applicationShouldHandleReopen(sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if !flag{
let sb = NSStoryboard(name: "Main", bundle: nil)
let controller = sb?.instantiateInitialController() as NSWindowController
controller.window?.makeKeyAndOrderFront(self)
self.window = controller.window
}
return true
}
But that requires that I set a ref to the window on my app delegate. Since that isn't required when the app initially starts I'm pretty positive I am doing something wrong while missing something obvious.
This solution also appears to work
func applicationShouldHandleReopen(sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if !flag{
for window in sender.windows{
if let w = window as? NSWindow{
w.makeKeyAndOrderFront(self)
}
}
}
return true
}
Here is a 3rd solution that I have also found works, from within your NSApplicationDelegate
:
var mainWindow: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
mainWindow = NSApplication.sharedApplication().windows[0] as! NSWindow
}
func applicationShouldHandleReopen(sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if !flag{
mainWindow.makeKeyAndOrderFront(nil)
}
return true
}
I have no idea why Apple doesn't provide guidance on this, or let you set the outlet from the storyboard for the window. It seems like a common thing to need. Maybe I am still just missing something.
回答1:
In case you are looking for a cocoa-based solution for non-document apps. This is the equivalent of Adam's second solution.
- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
{
if(!flag)
{
for(id const window in theApplication.windows)
{
[window makeKeyAndOrderFront:self];
}
}
return YES;
}
回答2:
Swift 3: In AppDelegate.swift add a variable of type NSWindow
lazy var windows = NSWindow()
and implement applicationShouldHandleReopen:
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if !flag {
for window in sender.windows {
window.makeKeyAndOrderFront(self)
}
}
return true
}
Or using forEach:
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if !flag {
sender.windows.forEach { $0.makeKeyAndOrderFront(self) }
}
return true
}
来源:https://stackoverflow.com/questions/27953139/how-to-handle-applicationshouldhandlereopen-in-a-non-document-based-storyboard-a