collectionView(_:didDeselectItemsAt:) is never called

自古美人都是妖i 提交于 2019-12-08 09:38:50

问题


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... :/


回答1:


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.




回答2:


We need to set NSCollectionView item selected:

 collectionview.isSelectable = true


来源:https://stackoverflow.com/questions/41570577/collectionview-diddeselectitemsat-is-never-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!