尝试识别右键单击NSStatusItem
我得到了一个建议(谢谢 Zoff Dino < / em>)使用NSClickGestureRecognizer
。但由于一些奇怪的原因,它不能正常运作。我能够识别左键单击(buttonMask = 0x1
)但不能右键单击(buttonMask = 0x2
)。这就是我希望它工作的方式,但事实并非如此:
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
if let button = statusItem.button {
// Add right click functionality
let gesture = NSClickGestureRecognizer()
gesture.buttonMask = 0x2 // right mouse
gesture.target = self
gesture.action = "rightClickAction:"
button.addGestureRecognizer(gesture)
}}
func rightClickAction(sender: NSGestureRecognizer) {
if let button = sender.view as? NSButton {
NSLog("rightClick")
}
}
更新
我仍然无法上班。不知何故,它没有对右键单击作出反应(但是在左键单击时更改代码)。我想一些非常简单的问题正在发生,似乎阻止了它的工作。甚至更奇怪的是
gesture.buttonMask = 0x1
在左键单击时起作用。
答案 0 :(得分:1)
替代解决方案而不是NSClickGestureRecognizer
是将自定义视图附加到状态栏并从那里处理事件。
缺点是你需要处理绘图和菜单委托方法。
这是一个简单的例子:
创建文件StatusItemView
NSView
import Cocoa
class StatusItemView: NSView, NSMenuDelegate {
//MARK: - Variables
weak var statusItem : NSStatusItem!
var menuVisible = false
var image : NSImage! {
didSet {
if image != nil {
statusItem.length = image.size.width
needsDisplay = true
}
}
}
//MARK: - Override functions
override func mouseDown(theEvent: NSEvent) {
if let hasMenu = menu {
hasMenu.delegate = self
statusItem.popUpStatusItemMenu(hasMenu)
needsDisplay = true
}
}
override func rightMouseDown(theEvent: NSEvent) {
Swift.print(theEvent)
}
//MARK: - NSMenuDelegate
func menuWillOpen(menu: NSMenu) {
menuVisible = true
needsDisplay = true
}
func menuDidClose(menu: NSMenu) {
menuVisible = false
menu.delegate = nil
needsDisplay = true
}
//MARK: - DrawRect
override func drawRect(dirtyRect: NSRect) {
statusItem.drawStatusBarBackgroundInRect(bounds, withHighlight:menuVisible)
let origin = NSMakePoint(2.0, 3.0) // adjust origin if necessary
image?.drawAtPoint(origin, fromRect: dirtyRect, operation: .CompositeSourceOver, fraction: 1.0)
}
}
在AppDelegate
中,您需要引用自定义菜单和NSStatusItem
实例的实例变量
@IBOutlet weak var menu : NSMenu!
var statusItem : NSStatusItem!
在applicationDidFinishLaunching
中创建视图并将其附加到状态项。请注意在安装后设置视图图像以确保考虑宽度。
func applicationDidFinishLaunching(aNotification: NSNotification) {
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) // NSVariableStatusItemLength)
let statusItemView = StatusItemView(frame: NSRect(x: 0.0, y: 0.0, width: statusItem.length, height: 22.0))
statusItemView.statusItem = statusItem;
statusItemView.menu = menu
statusItem.view = statusItemView
statusItemView.image = NSImage(named: NSImageNameStatusAvailable)
}
特殊情况控件 - 单击以触发右键单击功能未实现。