4

我正在构建一个状态栏应用程序,并希望根据用户是单击左键还是单击右键来调用不同的操作。这是我到目前为止所拥有的:

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")
}

我的函数没有被调用,我找不到我们的原因。我很感激任何帮助!

4

2 回答 2

15

你有没有尝试过:

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 == NSEvent.EventType.rightMouseUp {
        // Right button click
    } else {
        // Left button click
    }

}

感谢@dbrownjave 注意到 Swift 4 从NSEventType.rightMouseUpto的变化NSEvent.EventType.rightMouseUp

https://github.com/craigfrancis/datetime/blob/master/xcode/DateTime/AppDelegate.swift

于 2017-03-10T17:45:37.497 回答
2

更新:SWIFT 4

我已经更新(克雷格弗朗西斯)的答案

func doSomeAction(sender: NSStatusItem) {

    let event = NSApp.currentEvent!

    if event.type == NSEvent.EventType.rightMouseUp{
        // Right button click
    } else {
        // Left button click
    }
于 2018-02-18T16:23:12.090 回答