iosswiftswift2

How to vertically center UICollectionView content


I am trying to dynamically center the content of a UICollectionView, however none of the existing solutions take into account the fact that there might be more than one cell per row.

I have tried this center custom title in UINavigationBar? as well as both solutions here: UICollectionView vertically Centred, to no avail.

I am quite surprised iOS offers no way of doing this by default and even more that it is not possible to get the number of rows currently being displayed (which would've solved my issue as well). Also, I cannot get the size of the content (and not simply the size of the frame) which would also have helped me achieve the desired effect.

I have this:

 --------
|X X X X |
|X X X X |
|        |
|        |
 --------

But I want this:

 --------
|        |
|X X X X |
|X X X X |
|        |
 --------

Any help would be greatly appreciated,

Many thanks.


Solution

  • Now I understand your problem. Depending on the screen size you need another inset to make it look centered. Then you have to calculate it manually, but it should not be that hard. You know the available space, the number of items and the cell size. Just calculate the section inset from top.