Nicholas
Nicholas

Reputation: 755

Make UICollectionViewFlowLayout not centering cells on the same line

According to Apple Documents:

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

Now I have a collection view with 2 columns and cells varying in height. The problem is that the smaller cell is centered with the taller cell on its left/right, but not float up with the cell under it floats up too.

How can I make that happen?

What I have:

enter image description here

What I want:

enter image description here

It seems like that I should subclass UICollectionViewFlowLayout, but how should I accomplish this?

Upvotes: 1

Views: 995

Answers (2)

Nicola Giancecchi
Nicola Giancecchi

Reputation: 3065

The type of collection view layout you desire is called "waterfall layout". The implementation is a little bit tricky, since you need to override the basic behaviour of UICollectionViewFlowLayout.

I suggest you to take a look at 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

Upvotes: 3

Andrii Chernenko
Andrii Chernenko

Reputation: 10194

What you want to achieve is called "staggered layout". It was introduced by Pinterest in their iOS app.

You will need custom collection view layout, this tutorial will explain how. Alternatively, you can use one of the existing solutions, for example CHTCollectionViewWaterfallLayout.

Upvotes: 1

Related Questions