2016-08-17 5 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

更新...のようになります。(クレイグ・フランシス)の答え私は更新されてきた4

SWIFT

func doSomeAction(sender: NSStatusItem) { 

    let event = NSApp.currentEvent! 

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

このコードがなぜ機能するのか、問題を解決するために何を行うのですか? – Daniel

関連する問題