I have a UICollectionView
with random cells. Is there any method that allows me to center rows?
This is how it looks by default:
[ x x x x
In case anyone has a CollectionView that has 2 columns, and if number of items is odd, the last item should be center aligned. Then use this
DNLastItemCenteredLayout
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes *attribute in attributes) {
NSInteger itemCount = [self.collectionView.dataSource collectionView:self.collectionView
numberOfItemsInSection:attribute.indexPath.section];
if (itemCount % 2 == 1 && attribute.indexPath.item == itemCount - 1) {
CGRect originalFrame = attribute.frame;
attribute.frame = CGRectMake(self.collectionView.bounds.size.width/2-originalFrame.size.width/2,
originalFrame.origin.y,
originalFrame.size.width,
originalFrame.size.height);
}
}
return attributes;
}