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

强颜欢笑 提交于 2019-12-31 10:44:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!