How to show context menu in NSCollectionView

Issue #321

Detect locationInWindow in NSEvent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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

1
let frame = layoutAttributesForItem(at: IndexPath(item: index, section: 0))?.frame ?? .zero

Use Omnia

Omnia supports clicked indexPath for multi section NSCollectionView

1
2
3
collectionViewHandler.addMenuItem(title: "Add to Favorite", action: { item in
print(item)
})

Comments