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 ]
I had to do something like this, but needed all the cells in the one section. It was pretty simple to extend UICollectionViewFlowLayout
to center cells. I made a pod:
https://github.com/keighl/KTCenterFlowLayout
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 - How to center align the cells of a UICollectionView? - that goes into more details about the inset methods, although it's not quite trying to do the same thing that you are.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With