NSPanel not hiding when focus is lost

528 Views Asked by At

I am trying to create a window like Spotlight. As in Spotlight it should hide when the background is clicked. I tried doing it unsuccessfully with NSWindow but I was lead to believe using NSPanel instead would solve the problem. However, even when using NSPanel the window does not hide. Here is the code I'm using.

let panel = NSPanel(contentRect: CGRect(x: 0, y: 0, width: 200, height: 200), styleMask: [.titled, .nonactivatingPanel], backing: .buffered, defer: true)
panel.level = .mainMenu
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
panel.orderFrontRegardless()
1

There are 1 best solutions below

0
Asperi On BEST ANSWER

It is due to used window level (.mainMenu which is above all windows), so you need to hide it explicitly via delegate methods

so assuming you create window/panel in your controller, make that controller a delegate of window

panel.delegate = self

and implement something like

extension ViewController { // << your controller class here
   func windowDidResignKey(_ notification: Notification) {
       if let panel = notification.object as? NSWindow {
          panel.close()
       }
   }
}