在 macOS 上接受第一次鼠标点击

Dav*_*veC 3 macos cocoa subclass nscollectionview swift

我试图让 click-though 工作,以便我的应用程序即使在窗口处于非活动状态时也能响应鼠标点击。我有一个带有响应鼠标事件的 NSCollectionView 项目的 collectionView。我尝试将 collectViewItem 使用的视图子类化,并且还子类化了用于 NSCollectionView 的视图。它不起作用。子类视图的代码如下所示:

import Cocoa

class SubclassedView: NSView {

  override func draw(_ dirtyRect: NSRect) {
      super.draw(dirtyRect)
  }

  // adding this override should allow click-through so buttons can be clicked even with an inactive window
  // it doesn't work
  override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
      print("got first mouse")
      return true
  }

  override var acceptsFirstResponder :Bool {
      get {
          return true
      }
  }    
}
Run Code Online (Sandbox Code Playgroud)

有谁知道这里出了什么问题?

Fra*_*k R 10

我刚刚看到了同样的问题;子类化NSCollectionView或封闭NSClipViewNSScrollView对我也不起作用。

有效的是 subclassing NSView,就像您所做的那样:

class ClickThroughView: NSView {
    override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
        return true
    }
}
Run Code Online (Sandbox Code Playgroud)

...然后设置NSCollectionViewItem'sview以使用此类ClickThroughView

请注意,例如NSImageView坐在我们前面ClickThroughView会阻止点击事件到达我们的子类,因此您还需要子类NSImageView以接受点击。