I am currently using UICollectionView
for the user interface grid, and it works fine. However, I'd like to be enable horizontal scrolling. The grid supports 8 items per page and when the total number of items are, say 4, this is how the items should be arranged with horizontal scroll direction enabled:
0 0 x x
0 0 x x
Here 0 -> Collection Item and x -> Empty Cells
Is there a way to make them center aligned like:
x 0 0 x
x 0 0 x
So that the content looks more clean?
Also the below arrangement might also be a solution I am expecting.
0 0 0 0
x x x x
Working version of kgaidis's Objective C answer using Swift 3.0:
My solution for static sized collection view cells which need to have padding on left and right-
The top solutions here did not work for me out-of-the-box, so I came up with this which should work for any horizontal scrolling collection view with flow layout and only one section:
I have a tag bar in my app which uses an
UICollectionView
&UICollectionViewFlowLayout
, with one row of cells center aligned.To get the correct indent, you subtract the total width of all the cells (including spacing) from the width of your
UICollectionView
, and divide by two.The problem is this function -
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
is called before...
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
...so you can't iterate over your cells to determine the total width.
Instead you need to calculate the width of each cell again, in my case I use
[NSString sizeWithFont: ... ]
as my cell widths are determined by the UILabel itself.For those looking for a solution to center-aligned, dynamic-width collectionview cells, as I was, I ended up modifying Angel's answer for a left-aligned version to create a center-aligned subclass for
UICollectionViewFlowLayout
.CenterAlignedCollectionViewFlowLayout
Put this into your collection view delegate. It considers more of the the basic flow layout settings than the other answers and is thereby more generic.
swift version (thanks g0ld2k):