Joe*_*ard 12 macos menu nsstatusitem swift2
我一直在尝试开发一个位于Mac状态栏中的简单程序.我需要它,这样如果你左键单击,它会运行一个函数,但是如果你右键单击它会显示一个带有About和Quit项目的菜单.
我一直在寻找,但我能找到的只是命令或控制点击建议,但我宁愿不去这条路线.
在此先感谢,任何帮助表示赞赏!
Mic*_*lov 21
斯威夫特3
let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
if let button = statusItem.button {
button.action = #selector(self.statusBarButtonClicked(sender:))
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
}
func statusBarButtonClicked(sender: NSStatusBarButton) {
let event = NSApp.currentEvent!
if event.type == NSEventType.rightMouseUp {
print("Right click")
} else {
print("Left click")
}
}
Run Code Online (Sandbox Code Playgroud)
斯威夫特4
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
if let button = statusItem.button {
button.action = #selector(self.statusBarButtonClicked(_:))
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
}
func statusBarButtonClicked(sender: NSStatusBarButton) {
let event = NSApp.currentEvent!
if event.type == NSEvent.EventType.rightMouseUp {
print("Right click")
} else {
print("Left click")
}
}
Run Code Online (Sandbox Code Playgroud)
更长的帖子可在https://samoylov.eu/2016/09/14/handling-left-and-right-click-at-nsstatusbar-with-swift-3/获取
为此,您可以使用statusItem按钮属性.
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
let statusButton = statusItem!.button!
statusButton?.target = self // or wherever you implement the action method
statusButton?.action = "statusItemClicked:" // give any name you want
statusButton?.sendActionOn(Int((NSEventMask.LeftMouseUpMask | NSEventMask.RightMouseUpMask).rawValue)) // what type of action to observe
Run Code Online (Sandbox Code Playgroud)
然后你实现了action函数,在上面的代码中我把它命名为"statusItemClicked"
func statusItemClicked(sender: NSStatusBarButton!){
var event:NSEvent! = NSApp.currentEvent!
if (event.type == NSEventType.RightMouseUp) {
statusItem?.menu = myMenu //set the menu
statusItem?.popUpStatusItemMenu(myMenu)// show the menu
}
else{
// call your function here
}
}
Run Code Online (Sandbox Code Playgroud)