0

I have an app working from an extension in the Status Menu.

I have there a button "Settings" on which when the user taps should launch a particular view of my storyboard.

I have tried many different ways, Open NSWindowController from NSMenu, Cocoa - How to bring particular window to come in foreground from StatusMenu.

Here is my current code :

StatusMenu.swift

func showSettings() {

  var mainWindowController = MainWindowController()
  mainWindowController.showWindow(nil)

}

MainWindowController.swift

class MainWindowController: NSWindowController {

 override func windowDidLoad() {
   super.windowDidLoad()

   self.window?.center()
   self.window?.makeKeyAndOrderFront(nil)
   NSApp.activate(ignoringOtherApps: true)

   }

}
Antoine
  • 1,139
  • 9
  • 21

1 Answers1

0

The code posted has 2 potential issues:

  1. MainWindowController.init is not implemented by NSWindowController but NSObject, that means unlike for NSViewControllers, this does not lookup the Nib file of the same name. Use this:

    extension MainWindowController {
        convenience init() {
            self.init(windowNibName: .init(rawValue: "MainWindowController"))
        }
    }
    
  2. The resulting instance is referenced from mainWindowController, but this variable only has local scope to showSettings(). That means, once showSettings() is done, the garbage collector will release the object again. It's as good as never having stored it. You need to keep a permanent reference in an object that lives on, or as a global variable, as in:

     // Assuming your StatusMenu instance is strongly referenced for the whole runtime
     class StatusMenu {
         var mainWindowController: MainWindowController?
         func showSettings() {
            self.mainWindowController = MainWindowController()
            self.mainWindowController?.showWindow(nil)
         }
     }
    
ctietze
  • 2,805
  • 25
  • 46
  • I'm trying to implement your solution but I'm not able to use ".init"... Is it Swift 4? – Antoine Dec 13 '17 at 12:22
  • Yes, it's short for `NSNib.Name(rawValue:)` in this context; in Swift 3, you should be able to pass the String directly. – ctietze Dec 13 '17 at 12:29
  • OK thanks, I just tried and I have the error : "Failed to lad window nib file "MainWindowController", is the problem that my nib is in my storyboard ? – Antoine Dec 13 '17 at 12:32