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.
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
.
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.
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