NSCollectionView really weird behavior with selection.

I created an NSCollectionView in a view controller within a window of my app. I implemented NSCollectionViewDelegate, specifically:

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

This does work, but with a caveat: I have to first click on a blank space within the collection view's view, and then when I select a cell, it will call the method as expected. If I don't do this, nothing will happen when I select the cells. And I will have to do this every time I clicked something on that view controller that's outside the collection view.


Any idea?


The collection view does not take up the entire view controller, by the way, it's a subview of the NSViewController's view.

Accepted Reply

Found the problem. The problem did indeed is in the table view.


This SO question that I've asked has the answer:


https://stackoverflow.com/questions/54720493/horizontal-nscollectionview-in-vertical-nstableview-does-not-select-until-collec/54720963#54720963


Just subclass the NSTableView and override validateProposedFirstResponder(_:for:) for the collection view.

Replies

If you click on an item in the collection, then click again, do you get it selected?

Does the problem occur when you first load the view or anytime ?


Have you set

collectionview.isSelectable = true

Try also to allow for multiple selection to see what happens.


May read this for some other hints:

https://stackoverflow.com/questions/20380512/uicollectionview-diddeselectitematindexpath-not-called-if-cell-is-selected

Thanks for the response.

Yeah, I had them all set, and I did come across the question before this. The delegate methods are not called at all before I click somewhere within the collection view. So I can say that it wasn't really a problem with the delegate. I did verify that after I click somewhere inside the collection view's boundary it will start working just like normal.


Oh yeah, by the way, the NSCollectionView is in a prototype NSTableCellView if that's relevant, and the delegate is implemented within the table cell view's subclass.

Found the problem. The problem did indeed is in the table view.


This SO question that I've asked has the answer:


https://stackoverflow.com/questions/54720493/horizontal-nscollectionview-in-vertical-nstableview-does-not-select-until-collec/54720963#54720963


Just subclass the NSTableView and override validateProposedFirstResponder(_:for:) for the collection view.