简体   繁体   中英

NSPanel not hiding when focus is lost

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()

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()
       }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM