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