Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle applicationShouldHandleReopen in a Non-Document based Storyboard Application

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.

like image 230
AJ Venturella Avatar asked Jan 14 '15 21:01

AJ Venturella


2 Answers

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
    }
like image 153
balazs630 Avatar answered Sep 29 '22 15:09

balazs630


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;
}
like image 37
Wayne Dixon Avatar answered Sep 29 '22 16:09

Wayne Dixon