I have some Swift code that looks like this. However the menu item will just be greyed out and not work. I have tried different versions for the #selector
on the item, but so far nothing works.
class StatusBarController {
private var statusBar: NSStatusBar
private var statusItem: NSStatusItem
init() {
statusBar = NSStatusBar.init()
self.statusItem = statusBar.statusItem(withLength: NSStatusItem.variableLength)
self.state = FirebaseData()
self.startUpdate()
self.setupMenus()
}
func setupMenus() {
let menu = NSMenu()
menu.addItem(withTitle: "Play Pause", action: #selector(StatusBarController.onClickPlayPause), keyEquivalent: "1")
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
self.statusItem.menu = menu
}
@objc func onClickPlayPause(sender : NSMenuItem) {
if self.isRunning() {
self.pause()
} else if (self.state.intervalLeft != nil) {
self.resume()
} else {
self.startTimer(nil)
}
}
}
Can someone explain to me what I'm doing wrong here? Thank you!
CodePudding user response:
You have to set the target.
let playMenuItem = menu.addItem(withTitle: "Play Pause", action: #selector(onClickPlayPause), keyEquivalent: "1")
playMenuItem.target = self
The Quit
item works via First Responder.