我正在构建状态栏应用,并希望根据用户是向左还是向右单击来调用不同的操作。这是我到目前为止所做的:
var statusItem = NSStatusBar.system().statusItem(withLength: -1)
statusItem.action = #selector(AppDelegate.doSomeAction(sender:))
let leftClick = NSEventMask.leftMouseDown
let rightClick = NSEventMask.rightMouseDown
statusItem.button?.sendAction(on: leftClick)
statusItem.button?.sendAction(on: rightClick)
func doSomeAction(sender: NSStatusItem) {
print("hello world")
}
我的功能没有调用,我找不到原因。我感谢任何帮助!
答案 0 :(得分:7)
你试过了吗?
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
然后查看doSomeAction()
功能中按下了哪个鼠标按钮?
所以它看起来像......
let statusItem = NSStatusBar.system().statusItem(withLength: NSSquareStatusItemLength)
func applicationDidFinishLaunching(_ aNotification: Notification) {
if let button = statusItem.button {
button.action = #selector(self.doSomeAction(sender:))
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
}
}
func doSomeAction(sender: NSStatusItem) {
let event = NSApp.currentEvent!
if event.type == NSEventType.rightMouseUp {
// Right button click
} else {
// Left button click
}
}
https://github.com/craigfrancis/datetime/blob/master/xcode/DateTime/AppDelegate.swift
答案 1 :(得分:2)
已更新:SWIFT 4
我已经更新了(克雷格弗朗西斯)回答
func doSomeAction(sender: NSStatusItem) {
let event = NSApp.currentEvent!
if event.type == NSEvent.EventType.rightMouseUp{
// Right button click
} else {
// Left button click
}