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.
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
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With