简体   繁体   English

自动调整 NSCollectionViewItem 的大小以适应屏幕

[英]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.我正在尝试创建一个 NSCollectionView,它的项目适应可用空间,而不是为项目定义固定大小并相应地调整 NSCollectionView 的大小。

I couldn't figure out a way to achieve that with the NSCollectionViewFlowLayout as it requires a fixed size for it's items.我无法找到使用 NSCollectionViewFlowLayout 实现这一目标的方法,因为它需要固定大小的项目。 I came quite close to the desired result with the NSCollectionViewGridLayout.我非常接近 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.但是,在缩放包含 NSCollectionView 的窗口时,我需要 CollectionViewItems 来保持它们的纵横比(正方形),而 GridLayout 则根据它们的 min 和 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示例截图:扭曲的 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.我可能可以通过在网格中设置 maximumNumberOfColumns 来解决这个问题,具体取决于集合中的项目数和窗口大小,但这似乎有点麻烦。 Is there a better way to achieve the desired layout?有没有更好的方法来实现所需的布局? Maybe with a custom NSCollectionViewLayout?也许使用自定义 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).不要忘记将您的集合视图布局设置为“流”(在 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 {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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