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.
[........Collection View.........]
[..Cell..][..Cell..]
[____indent___] / 2
=
[_____][..Cell..][..Cell..][_____]
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.
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
CGFloat rightEdge = 0;
CGFloat interItemSpacing = [(UICollectionViewFlowLayout*)collectionViewLayout minimumInteritemSpacing];
for(NSString * tag in _tags)
rightEdge += [tag sizeWithFont:[UIFont systemFontOfSize:14]].width+interItemSpacing;
// To center the inter spacing too
rightEdge -= interSpacing/2;
// Calculate the inset
CGFloat inset = collectionView.frame.size.width-rightEdge;
// Only center align if the inset is greater than 0
// That means that the total width of the cells is less than the width of the collection view and need to be aligned to the center.
// Otherwise let them align left with no indent.
if(inset > 0)
return UIEdgeInsetsMake(0, inset/2, 0, 0);
else
return UIEdgeInsetsMake(0, 0, 0, 0);
}