UICollectionView flowLayout not wrapping cells correctly UICollectionView flowLayout not wrapping cells correctly ios ios

UICollectionView flowLayout not wrapping cells correctly


There is a bug in UICollectionViewFlowLayout's implementation of layoutAttributesForElementsInRect that causes it to return TWO attribute objects for a single cell in certain cases involving section insets. One of the returned attribute objects is invalid (outside the bounds of the collection view) and the other is valid. Below is a subclass of UICollectionViewFlowLayout that fixes the problem by excluding cells outside of the collection view's bounds.

// NDCollectionViewFlowLayout.h@interface NDCollectionViewFlowLayout : UICollectionViewFlowLayout@end// 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

See this.

Other answers suggest returning YES from shouldInvalidateLayoutForBoundsChange, but this causes unnecessary recomputations and doesn't even completely solve the problem.

My solution completely solves the bug and shouldn't cause any problems when Apple fixes the root cause.


Put this into the viewController that owns the collection view

- (void)viewWillLayoutSubviews{    [super viewWillLayoutSubviews];    [self.collectionView.collectionViewLayout invalidateLayout];}


i discovered similar problems in my iPhone application. Searching the Apple dev forum brought me this suitable solution which worked in my case and will probably in your case too:

Subclass UICollectionViewFlowLayout and override shouldInvalidateLayoutForBoundsChange to return YES.

//.h@interface MainLayout : UICollectionViewFlowLayout@end

and

//.m#import "MainLayout.h"@implementation MainLayout-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{    return YES;}@end