Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement contextual menu for NSCollectionView

In my OSX app I have a collection view which is a subclass of NSCollectionView.

I'm all satisfied with how the things are except the contextual menu, which I can't figure out yet.

So what I want is:

  • right-click on a collection view item brings up the contextual menu
  • the options picked from the menu (delete, edit, etc) are applied to the item that the click was performed on.

I know how to do it for NSOutlineView or NSTableView, but not for collection view.

I can't figure out how to get the index of the item clicked.

Does anyone have any ideas on how I can implement this?

Any kind of help is highly appreciated!

like image 477
Eugene Gordin Avatar asked Sep 30 '14 22:09

Eugene Gordin


Video Answer


1 Answers

Basically, all of our solutions are capable of addressing requirements, but I would like to make a supplement to swift3+, which I think is a complete solution.

/// 扩展NSCollectionView功能,增加常用委托
class ANCollectionView: NSCollectionView {
    // 扩展委托方式
    weak open var ANDelegate: ANCollectionViewDelegate?

    override func menu(for event: NSEvent) -> NSMenu? {
        var menu = super.menu(for: event);
        let point = self.convert(event.locationInWindow, from: nil)
        let indexPath = self.indexPathForItem(at: point);
        if ANDelegate != nil{
            menu = ANDelegate?.collectionView(self, menu: menu, at: indexPath);
        }
        return menu;
    }
}

/// 扩展NSCollectionView的委托
protocol ANCollectionViewDelegate : NSObjectProtocol {
    func collectionView(_ collectionView:NSCollectionView, menu:NSMenu?, at indexPath: IndexPath?) -> NSMenu?
}

This is what I wrote an extension, and I hope to help everyone.

like image 155
Simon Avatar answered Oct 21 '22 10:10

Simon