分配给 NSMenuItem 的操作似乎不起作用 [英] Actions assigned to NSMenuItem dont seem to work
问题描述
我正在尝试完全以编程方式构建 Mac 状态栏应用程序.一切似乎都工作正常,即菜单显示在 Mac 状态栏中,下拉菜单显示它应该如何.但是当我点击菜单项时,没有任何反应.我什至将目标函数更改为只执行打印到终端的基本任务,什么都不做.
I am attempting to build a Mac Status Bar App completely programmatically. Everything seems to be working fine, that is the menu shows up in the Mac status bar, the dropdown menu is displaying how it should. But when I click on the menu items, nothing happens. I even changed the target function to just doing the basic task of printing to the terminal, and nothing.
我认为问题出在这附近:
The issue lies somewhere around here I think:
menu.addItem(NSMenuItem(title: val, action: #selector(toggleService), keyEquivalent: ""))
该代码应该触发 > toggleService 函数.但它没有任何作用.问题是不是因为我只继承自 NSObject 类?
That code should fire off the > toggleService function. But it doesn't do anything. Could the issue be due to the fact that I am only inheriting from the NSObject class?
// StatusBar.swift
import Cocoa
class StatusBar: NSObject {
var menuButton = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
var menu = NSMenu()
var service = Service()
override init() {
super.init()
menuButton.button?.image = NSImage(named: NSImage.Name("icon"))
menuButton.menu = menu
menu.autoenablesItems = false
for (_, val) in service.list {
menu.addItem(NSMenuItem(title: val, action: #selector(toggleService), keyEquivalent: ""))
}
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit", action: #selector(quit), keyEquivalent: ""))
}
@objc func toggleService(sender: NSMenuItem) {
print ("Say Something.. anything??")
}
@objc func quit(sender: NSMenuItem) {
print ("Say Something.. anything??")
}
}
推荐答案
menuItem.target = self
您需要将目标设置为自己".NSMenuItems 有两个基本要求.一个动作,一个目标,
You need to set the target to 'self'. NSMenuItems have two basic requirements. An action, and a target,
动作
menuItem.action: #selector(YOURFUNCTION)
目标menuItem.target = self
所以为了让你的菜单项工作,用这个新的替换 for 循环(在你的 init 调用中):
So to get your menu items working, replace the for loop (within your init call) with this new one:
for (_, val) in service.list {
let menuItem = menu.addItem(NSMenuItem(title: val, action: #selector(toggleService), keyEquivalent: ""))
menuItem.target = self
}
这篇关于分配给 NSMenuItem 的操作似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!