Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSCollectionViewItem double-click action?

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

like image 982
indragie Avatar asked Oct 12 '09 00:10

indragie


2 Answers

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.

like image 161
green_knight Avatar answered Sep 22 '22 17:09

green_knight


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

like image 2
Ben Gottlieb Avatar answered Sep 19 '22 17:09

Ben Gottlieb