Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Created by Nick Snyder on 11/13/12.
// https://gist.github.com/nicksnyder/4075682
// http://stackoverflow.com/questions/12927027/uicollectionview-flowlayout-not-wrapping-cells-correctly-ios
// NDCollectionViewFlowLayout.h
@interface NDCollectionViewFlowLayout : UICollectionViewFlowLayout
@end
// Created by Nick Snyder on 11/13/12.
// https://gist.github.com/nicksnyder/4075682
// http://stackoverflow.com/questions/12927027/uicollectionview-flowlayout-not-wrapping-cells-correctly-ios
// NDCollectionViewFlowLayout.m
#import "NDCollectionViewFlowLayout.h"
@implementation NDCollectionViewFlowLayout
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
NSMutableArray *newAttributes = [NSMutableArray arrayWithCapacity:attributes.count];
for (UICollectionViewLayoutAttributes *attribute in attributes) {
if ((attribute.frame.origin.x + attribute.frame.size.width <= self.collectionViewContentSize.width) &&
(attribute.frame.origin.y + attribute.frame.size.height <= self.collectionViewContentSize.height)) {
[newAttributes addObject:attribute];
}
}
return newAttributes;
}
@end
@ionel71089
Copy link

ionel71089 commented Aug 16, 2013

@steipete Is this fix in PSTCollectionView ?

@jfahrenkrug
Copy link

jfahrenkrug commented Sep 12, 2013

Thanks very much!

I had to take into account the section inset in order for it to work for me:

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    NSMutableArray *newAttributes = [NSMutableArray arrayWithCapacity:attributes.count];
    for (UICollectionViewLayoutAttributes *attribute in attributes) {
        if ((attribute.representedElementCategory != UICollectionElementCategoryCell) || // always include everything that's not a cell
            ((attribute.frame.origin.x + attribute.frame.size.width <= (self.collectionViewContentSize.width - self.sectionInset.right)) &&
             (attribute.frame.origin.y + attribute.frame.size.height <= (self.collectionViewContentSize.height - self.sectionInset.bottom))))
        {
            [newAttributes addObject:attribute];
        }
    }
    return newAttributes;
}

@WenchaoD
Copy link

WenchaoD commented Apr 16, 2015

Wonderful~

@appleramos
Copy link

appleramos commented May 9, 2015

How can I implement this? I already made this and it is not called. Where should I call this? Thanks in advance

@narendrabade
Copy link

narendrabade commented May 11, 2017

How can I implement this? I already made this and it is not called. Where should I call this? Thanks in advance

@User2004
Copy link

User2004 commented Jan 25, 2019

Click here for set collectionview flow layout

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