Created
November 13, 2014 17:49
-
-
Save ArtSabintsev/8c096b410e490f6cb71e to your computer and use it in GitHub Desktop.
UICollectionFlowLayout - Cell Spacing in a UICollectionView Flow Layout.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// GiftCardFlowLayout.m | |
// ID.me Marketplace | |
// | |
// Created by Arthur Sabintsev on 9/7/14. | |
// Copyright (c) 2014 ID.me, Inc. All rights reserved. | |
// | |
#import "GiftCardFlowLayout.h" | |
@interface GiftCardFlowLayout () | |
@property (nonatomic, assign) CGFloat maximumSpacing; | |
@end | |
@implementation GiftCardFlowLayout | |
- (instancetype)init | |
{ | |
self = [super init]; | |
if (self) { | |
_maximumSpacing = 100.0f/2.0f; | |
} | |
return self; | |
} | |
// http://stackoverflow.com/a/19429189/814861 | |
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect | |
{ | |
NSArray *layoutAttributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy]; | |
NSUInteger attirbuteCount = [layoutAttributes count]; | |
for (NSUInteger i = 1; i < attirbuteCount; ++i) { | |
UICollectionViewLayoutAttributes *currentLayoutAttributes = layoutAttributes[i]; | |
UICollectionViewLayoutAttributes *previousLayoutAttributes = layoutAttributes[i - 1]; | |
NSInteger origin = CGRectGetMaxX(previousLayoutAttributes.frame); | |
CGFloat sum = origin + _maximumSpacing + CGRectGetWidth([currentLayoutAttributes frame]); | |
if (sum < self.collectionViewContentSize.width ) { | |
CGRect frame = [currentLayoutAttributes frame]; | |
frame.origin.x = origin + _maximumSpacing; | |
currentLayoutAttributes.frame = frame; | |
} | |
} | |
return layoutAttributes; | |
} | |
- (CGSize)collectionViewContentSize | |
{ | |
NSUInteger count = [self.collectionView.dataSource collectionView:self.collectionView numberOfItemsInSection:0]; | |
UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)[self.collectionView collectionViewLayout]; | |
CGFloat sizeFromItems = count * (layout.itemSize.width + _maximumSpacing); | |
CGFloat missingRightInsetSize = layout.sectionInset.right/2.0f; | |
CGFloat newContentSizeWidth = sizeFromItems + missingRightInsetSize; | |
return CGSizeMake(newContentSizeWidth, self.collectionView.frame.size.height); | |
} | |
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds | |
{ | |
return YES; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment