user688262
user688262

Reputation: 211

View in NSMenu not clickable if window is invisible

I experience a really strange behaviour with an NSMenu in an "Application is agent"-Application.

I have the following simple code to setup a titlebar icon with an NSMenu. The menu contains a customview with a NSSwitch button.

class AppDelegate: NSObject, NSApplicationDelegate {
    
   let statusBarItem = NSStatusBar.system.statusItem(withLength: -1)
    


    func applicationDidFinishLaunching(_ aNotification: Notification) {
        
        let icon = NSImage(imageLiteralResourceName:"flag")
        statusBarItem.image = icon
        
        let menu: NSMenu = NSMenu()
        var menuItem = NSMenuItem()
        
        let frame = CGRect(origin: .zero, size: CGSize(width: 100, height: 20))
        let viewHint = NSView(frame: frame)
        
        let switchButton = NSSwitch(frame: frame)
        viewHint.addSubview(switchButton)
        
        
        menuItem.view = viewHint
        
        menu.addItem(menuItem)
        
        statusBarItem.menu=menu
        
    }

It works quite good as long as the applications window is focussed.

When I close the applications main window, the titlebar is still visible (because it's an agent application). And now the switch button in the menu is not responsive anymore, meaning I cant switch it on or off. You can if double click on it really fast, but it's not the normal behaviour anymore and it has somehow to do with the hidden window. As I said, it's working if the window is visible.

Any ideas? Thanks!

Upvotes: 1

Views: 277

Answers (1)

ShaoJen Chen
ShaoJen Chen

Reputation: 700

You need to return acceptsFirstMouse as true in NSSwitch subclass.

And replace your code with

let switchButton = MySwitch(frame: frame)

Here is the subclass.

class MySwitch: NSSwitch {
    override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
        return true
    }
}

Upvotes: 0

Related Questions