deycall deycall - 6 months ago 73
Objective-C Question

How can I center rows in UICollectionView?

I have a

UICollectionView
with random cells. Is there any method that allows me to center rows?

This is how it looks by default:

[ x x x x x x ]
[ x x x x x x ]
[ x x ]


Here is what the desired layout looks like:

[ x x x x x ]
[ x x x x x ]
[ x x ]

lxt lxt
Answer

A bit of background first - a UICollectionView is combined with a UICollectionViewLayout which determines how the cells get placed in the view. This means a collection view is very flexible (you can create almost any layout with it), but also means modifying layouts can be a little confusing.

Creating an entirely new layout class is complex, so instead you want to try and modify the default layout (UICollectionViewFlowLayout) to get your center alignment. To make it even simpler, you probably want to avoid subclassing the flow layout itself.

Here's one approach (it may not be the best approach, but it's the first one I can think of) - split your cells into two sections, as follows:

[ x x x x x ] <-- Section 1 
[ x x x x x ] <-- Section 1 
[    x x    ] <-- Section 2 

This should be fairly straightforward, provided you know the width of your scroll view and the number of cells that can fit in each row.

Then, use the collectionView:layout:insetForSectionAtIndex: delegate method to set the margins for your second section so as it appears to be vertically centered. Once you've done this, you just need to ensure you recompute the appropriate section divisions/insets so both portrait and landscape orientations can be supported.

There is a somewhat similar question here - Center Align the contents in UICollectionView - that goes into more details about the inset methods, although it's not quite trying to do the same thing that you are.

Comments