6

How do I set an action for when a user double clicks an NSCollectionViewItem. NSTableView, for example, has the setDoubleAction method. Is there something similar for NSCollectionView?

Thanks

Lukas Würzburger
  • 6,543
  • 7
  • 41
  • 75
indragie
  • 18,002
  • 16
  • 95
  • 164

2 Answers2

4

I know this question is ancient, but it comes up as the third result on Google right now, and I've found a different and very straightforward method that I haven't seen documented elsewhere. (I don't just need to manipulate the represented item, but have more complex work to do in my app.)

NSCollectionView inherits from NSView, so you can simply create a custom subclass and override mouseDown. This is not completely without pitfalls - you need to check the click count, and convert the point from the main window to your collection view's coordinate, before using NSCollectionView's indexPathForItem method:

override func mouseDown(with theEvent: NSEvent) {
    if theEvent.clickCount == 2 {
        let locationInWindow = theEvent.locationInWindow
        let locationInView = convert(locationInWindow, from: NSApplication.shared.mainWindow?.contentView)


        if let doubleClickedItem = indexPathForItem(at: locationInView){
        // handle double click - I've created a DoubleClickDelegate 
        // (my collectionView's delegate, but you could use notifications as well)
...

This feels as if I've finally found the method Apple intended to be used - otherwise, there's no reason for indexPathForItem(at:) to exist.

Lukas Würzburger
  • 6,543
  • 7
  • 41
  • 75
green_knight
  • 1,319
  • 14
  • 26
2

You'd probably want to handle this in your NSCollectionViewItem, rather than the NSCollectionView itself (to work off your NSTableView analogy).

Lukas Würzburger
  • 6,543
  • 7
  • 41
  • 75
Ben Gottlieb
  • 85,404
  • 22
  • 176
  • 172
  • 1
    Thanks, I ended up just subclassing the prototype NSView of the NSCollectionView and adding a mouseDown handler. – indragie Oct 12 '09 at 21:18