2015-10-21 8 views
6

Ho cercato di sviluppare un semplice programma che si trova nella barra di stato del Mac. Ne ho bisogno in modo che se si fa clic con il tasto sinistro, viene eseguita una funzione, ma se si fa clic con il pulsante destro del mouse viene visualizzato un menu con un elemento Informazioni su e Esci.Barra di stato sinistra e clic destro Barra Mac Swift 2

Ho cercato ma tutto quello che ho trovato è stato comando o controllo dei suggerimenti di clic, tuttavia preferirei non seguire questa rotta.

Grazie in anticipo e qualsiasi aiuto apprezzato!

risposta

8

per questo è possibile utilizzare la proprietà del pulsante statusItem.

let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) 
    let statusButton = statusItem!.button! 
    statusButton?.target = self // or wherever you implement the action method 
    statusButton?.action = "statusItemClicked:" // give any name you want 
    statusButton?.sendActionOn(Int((NSEventMask.LeftMouseUpMask | NSEventMask.RightMouseUpMask).rawValue)) // what type of action to observe 

quindi di implementare la funzione di azione, nel codice sopra ho chiamato "statusItemClicked"

func statusItemClicked(sender: NSStatusBarButton!){ 
    var event:NSEvent! = NSApp.currentEvent! 
    if (event.type == NSEventType.RightMouseUp) { 
     statusItem?.menu = myMenu //set the menu 
     statusItem?.popUpStatusItemMenu(myMenu)// show the menu 
    } 
    else{ 
     // call your function here 
    } 
} 
+1

In Swift 2, l'uso dell'operatore '|' su 'NSEventMask' restituisce un errore. – beeb

+1

statusButton? .sendActionOn (Int (NSEventMask.RightMouseUpMask.rawValue | NSEventMask.LeftMouseUpMask.rawValue)) funziona con Swift 2 – Hampus

9

Swift 3

let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength) 

if let button = statusItem.button { 
    button.action = #selector(self.statusBarButtonClicked(sender:)) 
    button.sendAction(on: [.leftMouseUp, .rightMouseUp]) 
} 

func statusBarButtonClicked(sender: NSStatusBarButton) { 
    let event = NSApp.currentEvent! 

    if event.type == NSEventType.rightMouseUp { 
     print("Right click") 
    } else { 
     print("Left click") 
    } 
} 

Swift 4

let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) 

if let button = statusItem.button { 
    button.action = #selector(self.statusBarButtonClicked(_:)) 
    button.sendAction(on: [.leftMouseUp, .rightMouseUp]) 
} 

func statusBarButtonClicked(sender: NSStatusBarButton) { 
    let event = NSApp.currentEvent! 

    if event.type == NSEvent.EventType.rightMouseUp { 
     print("Right click") 
    } else { 
     print("Left click") 
    } 
} 

Un post più lungo è disponibile a https://samoylov.eu/2016/09/14/handling-left-and-right-click-at-nsstatusbar-with-swift-3/

Problemi correlati