2016-08-17 63 views
0

我正在構建一個狀態欄應用程序(Swift 3),並且想要根據用戶點擊左側還是右側來調用不同的操作。這是我到目前爲止:Swift:識別NSStatusItem上的左鍵和右鍵事件

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

我的功能沒有被調用,我找不到我們的原因。我感謝任何幫助!

回答

3

您是否嘗試過:

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

+0

這確實有效,但似乎只喜歡'.rightMouseUp',而不是'.rightMouseDown' – joe

+0

你也改變了'button.sendAction'行嗎? –

+0

doh!在'sendAction'中更改,不在聲明中!工作得很好,謝謝x) – joe

1

更新時間:SWIFT 4

我已經更新(克雷格·弗朗西斯)答案

func doSomeAction(sender: NSStatusItem) { 

    let event = NSApp.currentEvent! 

    if event.type == NSEvent.EventType.rightMouseUp{ 
     // Right button click 
    } else { 
     // Left button click 
    } 
+0

您可以補充一點,以瞭解爲什麼此代碼可以正常工作以及它如何解決問題? – Daniel