Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vertically center UICollectionView content

Tags:

ios

swift

swift2

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.

like image 793
Max Dum Avatar asked Nov 27 '15 16:11

Max Dum


2 Answers

Not sure why you can't get the size of the content — UICollectionView is a UIScrollView subclass, hence has access to the contentSize property. If you only need to center the cells in case they are all visible without scrolling, you can simply do the following:

collectionView.contentInset.top = max((collectionView.frame.height - collectionView.contentSize.height) / 2, 0)

This will also work in cases when the number of cells grows so that not all of them are visible on the screen and you start using vertical scrolling — the top inset would be set to 0.

like image 126
Alex Staravoitau Avatar answered Nov 04 '22 06:11

Alex Staravoitau


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.

like image 4
Darko Avatar answered Nov 04 '22 06:11

Darko