简体   繁体   中英

Auto resize NSCollectionViewItem to fit screen

I'm trying to create a NSCollectionView where it's items adapt to the available space rather than defining a fixed size for the items and resize the NSCollectionView accordingly.

I couldn't figure out a way to achieve that with the NSCollectionViewFlowLayout as it requires a fixed size for it's items. I came quite close to the desired result with the NSCollectionViewGridLayout. However I need the CollectionViewItems to keep their aspect ratio (squares) when scaling the window that contains the NSCollectionView, while the GridLayout scales the items accordingly to their min and maxItemSize. Depending on the window size and the number of items in the collection I end up with items that are not exactly squares.

Example screenshot: distorted NSCollectionViewItems

I could probably work around that with setting the maximumNumberOfColumns in the grid, depending on the number of items in the collection and the window size, however it seems to be a bit cumbersome. Is there a better way to achieve the desired layout? Maybe with a custom NSCollectionViewLayout?

You need to implement the following protocol in your controller:

NSCollectionViewDelegateFlowLayout

It has a lot of methods allowing fine-tuning items (size / position / margins). Dont forget to set your collection view layout to be "flow" (in IB).

Look for implementing the following methods:

func collectionView(collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAtIndex section: Int) -> NSEdgeInsets {

   ...

}

func collectionView(collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> NSSize {

   ...
}

func collectionView(collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM