我正在寻找一种方法来检测 NSStatusBarButton
右键单击(使用 Swift)并调用一个操作。
我目前是这样设置的:
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
if let button = statusItem.button {
button.image = NSImage(named: "myImage")
button.alternateImage = NSImage(named: "myImage")
button.action = Selector("myAction")
}
}
我想到了使用 button.rightMouseDown(<#theEvent: NSEvent#>)
(因为没有这样的“alternateAction”)但不幸的是,由于我刚刚开始编写 Mac 应用程序,所以我没有想出一些办法。
Update:
While searching for a way to do this I saw some threads telling to subclass a
NSView
but I don't se how this should work (This could be because I am really new to programming and don't even know how to "subclass"). Still I thought there was some easier way to use this since nearly everystatusBar
App that I know rects on right-clicks.
最佳答案
您可以子类化和重写mouseDown
方法,但是从 Mac OS X 10.10 (Yosemite) 开始,有一种更简单的方法:NSGestureRecognizer
及其子类:
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
if let button = statusItem.button {
button.image = NSImage(named: "myImage")
button.alternateImage = NSImage(named: "myImage")
button.action = Selector("myAction")
// Add right click functionality
let gesture = NSClickGestureRecognizer()
gesture.buttonMask = 0x2 // right mouse
gesture.target = self
gesture.action = "myRightClickAction:"
button.addGestureRecognizer(gesture)
}
}
func myRightClickAction(sender: NSGestureRecognizer) {
if let button = sender.view as? NSButton {
// Handle your right click event here
}
}
关于macos - 右键单击 NSStatusBarButton 时调用 Action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32188581/