tdenniston
tdenniston

Reputation: 3519

Filter or search NSCollectionView on macOS 10.11+

I'm looking for a way to filter the items displayed in an NSCollectionView. My NSCollectionView is managed using the 10.11 and up mechanism (i.e. with NSCollectionViewDataSource and NSCollectionViewDelegate). I can't seem to find any documentation on how this is done.

Is it possible to implement a filter for the visible items, and if so, is there documentation available to show me how it is done?

Upvotes: 1

Views: 388

Answers (1)

tdenniston
tdenniston

Reputation: 3519

There is probably a better way, but until that comes along here is the workaround I found that doesn't require modifying the data source (which seems slightly cleaner conceptually, as the data shouldn't change during filtering, just which items are rendered).

Assign a NSCollectionViewDelegateFlowLayout as your NSCollectionView delegate. Then implement the method collectionView(NSCollectionView, layout: NSCollectionViewLayout, sizeForItemAt: IndexPath) (docs). This allows you to specify the size per item during layout of the collection view. I simply returned a 0 width and height CGSize for the items which did not match the current filter string. Otherwise return the ItemSize of the given layout. On every action of the search field (e.g. every keystroke), I'm calling ReloadData() on the collection view, which causes a re-layout.

One issue with this is that you have to set a minimum inter-item and line spacing of 0, otherwise the 0-sized items will still get the inter-item spaces, which can produce unevenly spaced visible items.

I'd still love to know a better way, so if future readers have one, I'll change the accepted answer.

Upvotes: 1

Related Questions