Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I center the cells of a UICollectionView horizontally and vertically?

How do I vertically and horizontally center all the cells in a UICollectionView using UICollectionViewFlowLayout?

Flow layout leaves spacing on the right or bottom depending on the scroll direction. I want to set the same padding on all sides. I have played around with the sectionInset property of the UICollectionViewFlowLayout.

like image 859
jjxtra Avatar asked Mar 12 '13 07:03

jjxtra


2 Answers

I'd suggest implementing the UICollectionViewDelegateFlowLayout protocol to dynamically achieve horizontal and vertical centering of your cells. From the UICollectionViewDelegateFlowLayout Protocol Reference:

The UICollectionViewDelegateFlowLayout protocol defines methods that let you coordinate with a UICollectionViewFlowLayout object to implement a grid-based layout. The methods of this protocol define the size of items and the spacing between items in the grid.

All of the methods in this protocol are optional. If you do not implement a particular method, the flow layout delegate uses values in its own properties for the appropriate spacing information.

The flow layout object expects the collection view’s delegate object to adopt this protocol. Therefore, implement this protocol on object assigned to your collection view’s delegate property.

You'll probably be most interested in the collectionView:layout:insetForSectionAtIndex: method that can be used to adjust the inset on all four sides of the screen using something like UIEdgeInsetsMake. You can determine the insets according to the screen size by subtracting the appropriate amount, like the size of the cells, from the corresponding screen dimension (vertical or horizontal). Then, divide by two to get equal insets for a particular dimension.

like image 74
Daniel Zhang Avatar answered Nov 07 '22 13:11

Daniel Zhang


Used Section Inset?

Ok, try to play with minimumLineSpacing property and minimumInteritemSpacing property

minimumLineSpacing

For a vertically scrolling grid, this line spacing represents the minimum spacing between successive rows. For a horizontally scrolling grid, this value represents the minimum spacing between successive columns. This spacing is not applied to the space between the header and the first line or between the last line and the footer.

minimumInteritemSpacing

For a vertically scrolling grid, this spacing represents the minimum spacing between items in the same row. For a horizontally scrolling grid, this value represents the minimum spacing between items in the same column. This spacing is used to compute how many items can fit in a single line, but after the number of items is determined, the actual spacing may possibly be adjusted upward.

like image 1
Charan Avatar answered Nov 07 '22 13:11

Charan