back home

NSCollectionView - how to make collection items selectable

So I finally figured out how to easily make collection view items selectable (make them change background when selected). It was so obvious!

What’s funny it was so obvious it was really hard to find the answer - I googled couple of times and found answers how to make it the complex way.

But just recently found a simple way in one of Apple’s examples - by default Xcode creates NSView for view that will be used to create collection’s cells.

What’s interesting is that NSCollectionViewItem has already isSelected property so it supports selection out of the box. The only trick was to change NSView to NSBox, give it nice background (blue in my case) and bind it’s transparent property to NSCollectionViewItem’s isSelected property. Thanks to that you easily get a collection with selectable cells.

Damn, it’s so obvious now.

But what if you already created your cell’s view based on NSView? You can’t easily switch from NSView to NSBox by changing custom class from NSView to NSBox. Xcode will not update the view’s available properties.

Sure you could easily add a new view, drag and drop elements, make sure everything is all right, etc.

But there’s an easier way - because XIBs are XML files you can use your friendly editor and just change it. If you keep IDs intact all bindings will be functional.

You need to place your cell’s NSView that you created and move it inside NSBox, remove all properties add one new key=”contentView” (because NSBox has subviews) and you’re done!

It’s so simple to hack XIBs :-)