Search code examples
cocoadelegatesmouseeventappkitnscollectionview

collectionView(_:didDeselectItemsAt:) is never called


For some reason, my NSCollectionView (which uses a custom layout that I wrote) calls its delegate's collectionView(_:didSelectItemsAt:) function when I click an item, but not that same delegate's collectionView(_:didDeselectItemsAt:) when I click off it.

Here's my basic setup:

class MyCollectionViewContainer: NSViewController {
    fileprivate lazy var collectionView: NSCollectionView = {
        let collectionView = NSCollectionView()
        collectionView.delegate = self
        collectionView.dataSource = self

        collectionView.collectionViewLayout = self.customLayout
        collectionView.isSelectable = true
        collectionView.allowsEmptySelection = true
        collectionView.allowsMultipleSelection = false
    }()
}

extension MyCollectionViewContainer: NSCollectionViewDelegate {

    func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {

        print("Selected", indexPaths)

        // Mutate data to reflect that selection
    }

    func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
        print("Deselected", indexPaths)
    }
}

"Deselected" is never printed... :/


Solution

  • So it turns out my layout wasn't adding any supplementary views of type NSCollectionElementKindInterItemGapIndicator; apparently this is the view that the collection view uses to detect when you click off an item. My quick solution was to add one huge one to my layout that spans the entire collection view, and make its Z index below that of all other items and supplementary views.