79

I have a UICollectionView with a FLowLayout. It will work as I expect most of the time, but every now and then one of the cells does not wrap properly. For example, the the cell that should be on in the first "column" of the third row if actually trailing in the second row and there is just an empty space where it should be (see diagram below). All you can see of this rouge cell is the left hand side (the rest is cut off) and the place it should be is empty.

This does not happen consistently; it is not always the same row. Once it has happened, I can scroll up and then back and the cell will have fixed itself. Or, when I press the cell (which takes me to the next view via a push) and then pop back, I will see the cell in the incorrect position and then it will jump to the correct position.

The scroll speed seems to make it easier to reproduce the problem. When I scroll slowly, I can still see the cell in the wrong position every now and then, but then it will jump to the correct position straight away.

The problem started when I added the sections insets. Previously, I had the cells almost flush against the collection bounds (little, or no insets) and I did not notice the problem. But this meant the right and left of the collection view was empty. Ie, could not scroll. Also, the scroll bar was not flush to the right.

I can make the problem happen on both Simulator and on an iPad 3.

I guess the problem is happening because of the left and right section insets... But if the value is wrong, then I would expect the behavior to be consistent. I wonder if this might be a bug with Apple? Or perhaps this is due to a build up of the insets or something similar.

Illustration of problem and settings


Follow up: I have been using this answer below by Nick for over 2 years now without a problem (in case people are wondering if there are any holes in that answer - I have not found any yet). Well done Nick.

0

12 Answers 12

95

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.

4
  • Thanks! I was just starting to play with collectionView (if you want to spam Apple about this, here's the rdar reference openradar.appspot.com/12433891)
    – Vinzzz
    Feb 20, 2013 at 14:52
  • @NickSnyder I was having this issue with PSTCollectionView and my section headers weren't appearing on ios 5. I added [[attribute valueForKey:@"elementKind"] isEqualToString:@"UICollectionElementKindSectionHeader"] || to the if Aug 20, 2013 at 13:24
  • Rather than checking individual params of the rect, you could just use CGRectIntersectsRect(attribute.frame, rect) Apr 14, 2014 at 15:55
  • 1
    @richarddas No, you don't want to check if the rects intersect. In fact, all of the cells (valid or invalid) will intersect the bounds rect of the collection view. You want to check if any part of the rect falls outside the bounds, which is what my code does. Apr 16, 2014 at 2:04
8

Put this into the viewController that owns the collection view

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    [self.collectionView.collectionViewLayout invalidateLayout];
}
4
  • Where do you put that?
    – fatuhoku
    Aug 23, 2014 at 9:38
  • Into the viewController that owns the collection view Aug 23, 2014 at 9:40
  • 1
    it causes an infinite loop if calling from the viewController for me
    – Hofi
    Aug 24, 2017 at 21:47
  • As noted by DHennessy13, this current solution is good but may be imperfect as it will invalidateLayout when rotating the screen (and for most cases it shouldn't). An improvement could be to set a flag in order to invalidateLayout only once.
    – Cœur
    Sep 17, 2018 at 5:13
8

A Swift version of Nick Snyder's answer:

class NDCollectionViewFlowLayout : UICollectionViewFlowLayout {
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes = super.layoutAttributesForElements(in: rect)
        let contentSize = collectionViewContentSize
        return attributes?.filter { $0.frame.maxX <= contentSize.width && $0.frame.maxY < contentSize.height }
    }
}
1
  • 2
    this completely made the CollectionViewCell disappear... Any other possible solution?
    – Giggs
    Jul 14, 2017 at 9:24
7

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
2
  • This only partly solves the problem I'm having with this issue. The cell does indeed go to the correct place when the row appears. However, just before it appears I still get a cell appearing off the side. Nov 8, 2012 at 11:00
  • Careful — doing this will cause layout to be run every time you scroll. This can severely impact performance.
    – fatuhoku
    Aug 23, 2014 at 9:38
5

I've had this problem as well for a basic gridview layout with insets for margins. The limited debugging I've done for now is implementing - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect in my UICollectionViewFlowLayout subclass and by logging what the super class implementation returns, which clearly shows the problem.

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *attrsList = [super layoutAttributesForElementsInRect:rect];

    for (UICollectionViewLayoutAttributes *attrs in attrsList) {
        NSLog(@"%f %f", attrs.frame.origin.x, attrs.frame.origin.y);
    }

    return attrsList;
}

By implementing - (UICollectionViewLayoutAttributes *)initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath I can also see that it seems to return the wrong values for itemIndexPath.item == 30, which is factor 10 of my gridview's number of cells per line, not sure if that's relevant.

- (UICollectionViewLayoutAttributes *)initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath {
    UICollectionViewLayoutAttributes *attrs = [super initialLayoutAttributesForAppearingItemAtIndexPath:itemIndexPath];

    NSLog(@"initialAttrs: %f %f atIndexPath: %d", attrs.frame.origin.x, attrs.frame.origin.y, itemIndexPath.item);

    return attrs;
}

With a lack of time for more debugging, the workaround I've done for now is reduced my collectionviews width with an amount equal to the left and right margin. I have a header that still needs the full width so I've set clipsToBounds = NO on my collectionview and then also removed the left and right insets on it, seems to work. For the header view to then stay in place you need to implement frame shifting and sizing in the layout methods that are tasked with returning layoutAttributes for the header view.

1
4

I have added a bug report to Apple. What works for me is to set bottom sectionInset to a value less than top inset.

3

I was experiencing the same cell-deplacing-problem on the iPhone using a UICollectionViewFlowLayout and so I was glad finding your post. I know you are having the problem on an iPad, but I am posting this because I think it is a general issue with the UICollectionView. So here is what I found out.

I can confirm that the sectionInset is relevant to that problem. Besides that the headerReferenceSize also has influence whether a cell is deplaced or not. (This makes sense since it is needed for calcuating the origin.)

Unfortunately, even different screen sizes have to be taken into account. When playing around with the values for these two properties, I experienced that a certain configuration worked either on both (3.5" and 4"), on none, or on only one of the screen sizes. Usually none of them. (This also makes sense, since the bounds of the UICollectionView changes, therefore I did not experience any disparity between retina and non-retina.)

I ended up setting the sectionInset and headerReferenceSize depending on the screen size. I tried about 50 combinations until I found values under which the problem did not occure anymore and the layout was visually acceptable. It is very difficult to find values which work on both screen sizes.

So summarizing, I just can recommend you to play around with the values, check these on different screen sizes and hope that Apple will fix this issue.

3

I've just encountered a similar issue with cells disappearing after UICollectionView scroll on iOS 10 (got no problems on iOS 6-9).

Subclassing of UICollectionViewFlowLayout and overriding method layoutAttributesForElementsInRect: doesn't work in my case.

The solution was simple enough. Currently I use an instance of UICollectionViewFlowLayout and set both itemSize and estimatedItemSize (I didn't use estimatedItemSize before) and set it to some non-zero size. Actual size is calculating in collectionView:layout:sizeForItemAtIndexPath: method.

Also, I've removed a call of invalidateLayout method from layoutSubviews in order to avoid unnecessary reloads.

2
  • where did set the itemsize and estimatedItemsize in the uicollectionviewflowlayout? Nov 10, 2016 at 16:51
  • UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init]; [flowLayout setItemSize:CGSizeMake(200, 200)]; [flowLayout setEstimatedItemSize:CGSizeMake(200, 200)]; self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout]; Nov 25, 2016 at 11:04
2

I just experienced a similar issue but found a very different solution.

I am using a custom implementation of UICollectionViewFlowLayout with a horizontal scroll. I am also creating custom frame locations for each cell.

The problem that I was having was that [super layoutAttributesForElementsInRect:rect] wasn't actually returning all of the UICollectionViewLayoutAttributes that should be displayed on screen. On calls to [self.collectionView reloadData] some of the cells would suddenly be set to hidden.

What I ended up doing was to create a NSMutableDictionary that cached all of the UICollectionViewLayoutAttributes that I have seen so far and then include any items that I know should be displayed.

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {

    NSArray * originAttrs = [super layoutAttributesForElementsInRect:rect];
    NSMutableArray * attrs = [NSMutableArray array];
    CGSize calculatedSize = [self calculatedItemSize];

    [originAttrs enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes * attr, NSUInteger idx, BOOL *stop) {
        NSIndexPath * idxPath = attr.indexPath;
        CGRect itemFrame = [self frameForItemAtIndexPath:idxPath];
        if (CGRectIntersectsRect(itemFrame, rect))
        {
            attr = [self layoutAttributesForItemAtIndexPath:idxPath];
            [self.savedAttributesDict addAttribute:attr];
        }
    }];

    // We have to do this because there is a bug in the collection view where it won't correctly return all of the on screen cells.
    [self.savedAttributesDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSArray * cachedAttributes, BOOL *stop) {

        CGFloat columnX = [key floatValue];
        CGFloat leftExtreme = columnX; // This is the left edge of the element (I'm using horizontal scrolling)
        CGFloat rightExtreme = columnX + calculatedSize.width; // This is the right edge of the element (I'm using horizontal scrolling)

        if (leftExtreme <= (rect.origin.x + rect.size.width) || rightExtreme >= rect.origin.x) {
            for (UICollectionViewLayoutAttributes * attr in cachedAttributes) {
                [attrs addObject:attr];
            }
        }
    }];

    return attrs;
}

Here is the category for NSMutableDictionary that the UICollectionViewLayoutAttributes are being saved correctly.

#import "NSMutableDictionary+CDBCollectionViewAttributesCache.h"

@implementation NSMutableDictionary (CDBCollectionViewAttributesCache)

- (void)addAttribute:(UICollectionViewLayoutAttributes*)attribute {

    NSString *key = [self keyForAttribute:attribute];

    if (key) {

        if (![self objectForKey:key]) {
            NSMutableArray *array = [NSMutableArray new];
            [array addObject:attribute];
            [self setObject:array forKey:key];
        } else {
            __block BOOL alreadyExists = NO;
            NSMutableArray *array = [self objectForKey:key];

            [array enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes *existingAttr, NSUInteger idx, BOOL *stop) {
                if ([existingAttr.indexPath compare:attribute.indexPath] == NSOrderedSame) {
                    alreadyExists = YES;
                    *stop = YES;
                }
            }];

            if (!alreadyExists) {
                [array addObject:attribute];
            }
        }
    } else {
        DDLogError(@"%@", [CDKError errorWithMessage:[NSString stringWithFormat:@"Invalid UICollectionVeiwLayoutAttributes passed to category extension"] code:CDKErrorInvalidParams]);
    }
}

- (NSArray*)attributesForColumn:(NSUInteger)column {
    return [self objectForKey:[NSString stringWithFormat:@"%ld", column]];
}

- (void)removeAttributesForColumn:(NSUInteger)column {
    [self removeObjectForKey:[NSString stringWithFormat:@"%ld", column]];
}

- (NSString*)keyForAttribute:(UICollectionViewLayoutAttributes*)attribute {
    if (attribute) {
        NSInteger column = (NSInteger)attribute.frame.origin.x;
        return [NSString stringWithFormat:@"%ld", column];
    }

    return nil;
}

@end
2
  • I'm using horizontal scrolling too, I manage to fix the issue using your solution, but after performing segue to other view and came back, the content size seemed to be wrong when there are extra items which doesn't divide into columns equally.
    – morph85
    Jan 30, 2016 at 9:02
  • I found a solution to fix issue where cell getting hidden after performing segue and back to collection view. Try not to set estimatedItemSize in collectionViewFlowLayout; set itemSize directly.
    – morph85
    Jan 30, 2016 at 10:05
2

The above answers don't work for me, but after downloading the images, I replaced

[self.yourCollectionView reloadData]

with

[self.yourCollectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];

to refresh and it can show all cells correctly, you can try it.

0

This might be a little late but make sure you are setting your attributes in prepare() if possible.

My issue was that the cells were laying out, then getting update in layoutAttributesForElements. This resulted in a flicker effect when new cells came into view.

By moving all the attribute logic into prepare, then setting them in UICollectionViewCell.apply() it eliminated the flicker and created butter smooth cell displaying 😊

-1

Swift 5 version of Nick Snyder answer:

class NDCollectionViewFlowLayout: UICollectionViewFlowLayout {
    open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes = super.layoutAttributesForElements(in: rect)
        var newAttributes = [AnyHashable](repeating: 0, count: attributes?.count ?? 0)
        for attribute in attributes ?? [] {
            if (attribute.frame.origin.x + attribute.frame.size.width <= collectionViewContentSize.width) && (attribute.frame.origin.y + attribute.frame.size.height <= collectionViewContentSize.height) {
                newAttributes.append(attribute)
            }
        }
        return newAttributes as? [UICollectionViewLayoutAttributes]
    }
}

Or you could use extension of UICollectionViewFlowLayout:

extension UICollectionViewFlowLayout {
    open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes = super.layoutAttributesForElements(in: rect)
        var newAttributes = [AnyHashable](repeating: 0, count: attributes?.count ?? 0)
        for attribute in attributes ?? [] {
            if (attribute.frame.origin.x + attribute.frame.size.width <= collectionViewContentSize.width) && (attribute.frame.origin.y + attribute.frame.size.height <= collectionViewContentSize.height) {
                newAttributes.append(attribute)
            }
        }
        return newAttributes as? [UICollectionViewLayoutAttributes]
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.