Issue #321
Detect locationInWindow in NSEvent
class ClickedCollectionView: NSCollectionView {
var clickedIndex: Int?
override func menu(for event: NSEvent) -> NSMenu? {
clickedIndex = nil
let point = convert(event.locationInWindow, from: nil)
for index in 0..<numberOfItems(inSection: 0) {
let frame = frameForItem(at: index)
if NSMouseInRect(point, frame, isFlipped) {
clickedIndex = index
break
}
}
return super.menu(for: event)
}
}
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Delete", action: #selector(didSelectDelete(_:)), keyEquivalent: ""))
collectionView.menu = menu
@objc func didSelectDelete(_ item: NSMenuItem) {
guard
let index = collectionView.clickedIndex,
index < notes.count
else {
return
}
let indexPath = IndexPath(item: index, section: 0)
notes.remove(at: index)
collectionView.deleteItems(at: Set(arrayLiteral: indexPath))
}
For NSCollectionView with more than 1 sections
let frame = layoutAttributesForItem(at: IndexPath(item: index, section: 0))?.frame ?? .zero
Use Omnia
Omnia supports clicked indexPath for multi section NSCollectionView
collectionViewHandler.addMenuItem(title: "Add to Favorite", action: { item in
print(item)
})