Skip to content

Instantly share code, notes, and snippets.

@stevestreza
Created October 27, 2012 17:55
Show Gist options
  • Select an option

  • Save stevestreza/3965512 to your computer and use it in GitHub Desktop.

Select an option

Save stevestreza/3965512 to your computer and use it in GitHub Desktop.
A UICollectionViewFlowLayout that supports flexible-width cells, fixed-width margins between cells, and centering the cells.
//
// CHTCenteredCellLayout.m
//
// Created by Steve Streza on 10/25/12.
// Use however you like.
//
#import "CHTCenteredCellLayout.h"
@implementation CHTCenteredCellLayout
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
// Break the attributes up into rows based on their frame.origin.y values
NSMutableDictionary *rows = [NSMutableDictionary dictionary];
[attributes enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
UICollectionViewLayoutAttributes *attribute = (UICollectionViewLayoutAttributes *)object;
NSNumber *originY = @(attribute.frame.origin.y);
NSMutableArray *cells = rows[originY];
if(!cells){
cells = rows[originY] = [NSMutableArray array];
}
[cells addObject:attribute];
}];
double rowWidth = self.collectionView.frame.size.width;
[rows enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSArray *cellAttributes = (NSArray *)obj;
// Figure out the total width of the cells available in the row, plus gutters.
double gutter = 10;
__block double totalWidth = 0;
[cellAttributes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UICollectionViewLayoutAttributes *attributes = (UICollectionViewLayoutAttributes *)obj;
totalWidth += attributes.frame.size.width;
totalWidth += gutter;
}];
totalWidth -= gutter;
// Start at offsetX, then iterate through all the cells in the row, and update their frames.
__block double offsetX = (rowWidth - totalWidth) / 2;
[cellAttributes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UICollectionViewLayoutAttributes *attributes = (UICollectionViewLayoutAttributes *)obj;
CGRect frame = attributes.frame;
frame.origin.x = round(offsetX);
attributes.frame = frame;
offsetX += attributes.frame.size.width + gutter;
}];
}];
return attributes;
}
@end
//
// CHTCenteredCellLayout.h
//
// Created by Steve Streza on 10/25/12.
// Use however you like.
//
#import <UIKit/UIKit.h>
@interface CHTCenteredCellLayout : UICollectionViewFlowLayout
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment