NSClickGestureRecognizer

NSClickGestureRecognizer

试图识别一个右键点击一个NSStatusItem我得到了一个建议(多亏了佐夫迪诺)使用一个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在鼠标左键上工作。

最佳答案

另一种解决方案而不是NSClickGestureRecognizer是将自定义视图附加到状态栏并从中处理事件。
一个小缺点是你必须处理绘图和菜单委托方法。
这里有一个简单的例子:
创建一个文件StatusItemViewa subclass ofNSView

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)
  }

特殊情况控制点击触发右键点击功能未实现。

10-08 13:25