使 UICollectionViewFlowLayout 不在同一行上居中单元格

Make UICollectionViewFlowLayout not centering cells on the same line

根据 Apple 文档:

If you want to specify different sizes for your cells, you must implement the collectionView:layout:sizeForItemAtIndexPath: method on the collection view delegate. You can use the provided index path information to return the size of the corresponding item. During layout, the flow layout object centers items vertically on the same line, as shown in Figure 3-2. The overall height or width of the line is then determined by the largest item in that dimension.

https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/UsingtheFlowLayout/UsingtheFlowLayout.html#//apple_ref/doc/uid/TP40012334-CH3-SW1

现在我有一个包含 2 列和高度不同的单元格的集合视图。问题是较小的单元格在其 left/right 上以较高的单元格为中心,但不会向上浮动,它下面的单元格也向上浮动。

我怎样才能做到这一点?

我有:

我想要的:

我似乎应该将 UICollectionViewFlowLayout 子类化,但我应该如何实现它?

你想要达到的目标叫做"staggered layout"。它由 Pinterest 在其 iOS 应用程序中引入。

您将需要自定义集合视图布局,this tutorial will explain how. Alternatively, you can use one of the existing solutions, for example CHTCollectionViewWaterfallLayout

您想要的集合视图布局类型称为 "waterfall layout"。实现有点棘手,因为您需要覆盖 UICollectionViewFlowLayout 的基本行为。

我建议你看看this tutorial by Ray Wenderlich for building a waterfall layout from the ground, or - if you desire an already packed library - using a library on GitHub, like CHTCollectionViewWaterfallLayout, WaterfallCollectionView or CollectionViewWaterfallLayout