Skip to content

Instantly share code, notes, and snippets.

@tyrone-sudeium
Last active December 11, 2015 11:29
Show Gist options
  • Save tyrone-sudeium/4594251 to your computer and use it in GitHub Desktop.
Save tyrone-sudeium/4594251 to your computer and use it in GitHub Desktop.
A horizontally paging, but vertically-flowing UICollectionViewFlowLayout. Oddly, gists don't let you enter markdown into the description, so see the comment below for a description of what it does. Make sure you set its flow direction to **vertical**, even though it'll page horizontally.
@interface HorizontallyPagingCollectionViewFlowLayout : UICollectionViewFlowLayout
@end
@implementation HorizontallyPagingCollectionViewFlowLayout
- (CGSize) collectionViewContentSize
{
CGSize superSize = [super collectionViewContentSize];
CGSize frameSize = self.collectionView.frame.size;
NSInteger pages = ceilf(superSize.height / frameSize.height);
if (superSize.height >= frameSize.height) {
// multipage
return CGSizeMake(frameSize.width * pages, frameSize.height);
} else {
return superSize;
}
}
- (NSArray*) layoutAttributesForElementsInRect:(CGRect)rect
{
CGSize frameSize = self.collectionView.frame.size;
NSInteger minPage = floorf(rect.origin.x / frameSize.width);
NSInteger maxPage = floorf((rect.origin.x + rect.size.width) / frameSize.width);
CGRect transformedFrame = CGRectMake(0, minPage * frameSize.height, frameSize.width, frameSize.height + (maxPage * frameSize.height));
NSArray *attributesList = [super layoutAttributesForElementsInRect: transformedFrame];
for (UICollectionViewLayoutAttributes *attributes in attributesList) {
if (attributes.frame.origin.y >= self.collectionView.frame.size.height) {
CGFloat parentHeight = self.collectionView.frame.size.height;
NSInteger page = floorf(attributes.frame.origin.y / parentHeight);
CGRect frame = attributes.frame;
frame.origin.y -= (page * parentHeight);
frame.origin.x += (page * self.collectionView.frame.size.width);
attributes.frame = frame;
}
}
return attributesList;
}
@end
@tyrone-sudeium
Copy link
Author

Standard horizontal flow layout gives you:

[a] [d] | [g]
[b] [e] | [h]
[c] [f] | [i]

This flow layout gives you:

[a] [b] | [g] [h]
[c] [d] | [i]
[e] [f] |

Legend:
[x] = Collection view cell
| = Page separator

This results in a similar "paging grid" style to the Springboard.
Make sure you set the Flow Layout direction to Vertical!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment