I'm currently trying to build a menubar app. Therefore I need a NSWindowController for an login field. It must be possible to open this NSWindowController when pressing a menu item and also close that window when the user clicked on cancel.
I used showWindow(self)
and NSApp.hide(self)
but this didn’t work for me. So has anyone an idea what I can try?
Assuming you are using Storyboard
NSWindowController
to the storyboard and uncheck visible at launch
of the window.In AppDelegate
create a property windowController
var windowController : NSWindowController!
In AppDelegate
create an IBAction
.
In the action get the main storyboard with
let mainStoryBoard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil)
Then instantiate and assign the window controller (the identifier must match the storyboard identifier)
windowController = mainStoryBoard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "Login")) as! NSWindowController
Get the associated view controller (LoginController
is the custom class of the view controller)
let loginController = windowController.window!.contentViewController as! LoginController
Show the main window
windowController.showWindow(self)
In Interface Builder connect the NSMenuItem
to First Responder
(red cube) and then to the created IBAction
.
You can close the window either with the red close
button or you need to add custom logic.
If you use a XIB create an NSWindowController
subclass and load the XIB with windowController = MyWindowController(window: nil)
, activate your app with NSApp.activate(ignoringOtherApps: true)
get the associated window with let controllerWindow = windowController.window!
and show the window with controllerWindow.makeKeyAndOrderFront(self)