By lindon fox


2012-10-17 04:18:06 8 Comments

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.

11 comments

@Michael 2018-05-04 21:37:17

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 😊

@Patrick Pijnappel 2015-07-03 12:06:41

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 }
    }
}

@Giggs 2017-07-14 09:24:47

this completely made the CollectionViewCell disappear... Any other possible solution?

@Andrey Seredkin 2016-10-31 09:44:58

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.

@Garrett Cox 2016-11-10 16:51:10

where did set the itemsize and estimatedItemsize in the uicollectionviewflowlayout?

@Andrey Seredkin 2016-11-25 11:02:48

If you create CollectionView in code, then:

@Andrey Seredkin 2016-11-25 11:04:08

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init]; [flowLayout setItemSize:CGSizeMake(200, 200)]; [flowLayout setEstimatedItemSize:CGSizeMake(200, 200)]; self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];

@wmurmann 2018-04-10 01:25:23

Setting estimatedItemSize did it for me

@Nick Snyder 2012-11-14 23:55:31

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.

@Patrick Tescher 2012-11-21 22:10:21

FYI this bug also crops up with horizontal scrolling. Replacing x with y and width with height makes this patch work.

@Vinzzz 2013-02-20 14:52:35

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)

@Nick Snyder 2013-04-12 18:40:03

Thanks Patrick and Yanik. I updated my answer to support vertical scrolling as well.

@Lescai Ionel 2013-08-20 13:24:58

@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

@Rpranata 2014-04-07 06:04:55

I stumbled upon this page a year ago and this solved my problem. Thanks! However, I was wondering whether this problem has been fixed internally by Apple. Cheers.

@cleverbit 2014-04-14 15:55:38

Rather than checking individual params of the rect, you could just use CGRectIntersectsRect(attribute.frame, rect)

@Nick Snyder 2014-04-16 02:04:35

@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.

@nonamelive 2014-04-18 23:11:42

@Rpranata As of iOS 7.1, this bug has not been fixed. Sigh.

@Rpranata 2014-04-21 05:31:57

@nonamelive Thanks for conforming that. I was so tempted to remove this from the code base. Turns out I still need it. sigh

@Prem Baranwal 2014-08-15 06:24:04

@NickSnyder Nick I'm facing the same issue after using collection view inside table view cell.The cells inside the internal collection view are rearranged and sometimes disappearing.Please help me how i am supposed to user your code.I am just setting your custom layout instead of UICollectionview layout.But - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect where to use this method?

@sudo 2015-04-17 07:26:44

Maybe I'm using this wrong, but on iOS 8.3 in Swift, this is causing subviews on the right that used to be cut off to not appear at all. Anyone else?

@Deekor 2015-05-22 04:07:51

Have they not fixed this 3 years later?

@Yao Li 2015-06-26 18:40:23

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.

@Peter Lapisu 2014-06-03 08:48:32

Put this into the viewController that owns the collection view

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

@fatuhoku 2014-08-23 09:38:14

Where do you put that?

@Peter Lapisu 2014-08-23 09:40:10

Into the viewController that owns the collection view

@pawi 2014-11-24 12:43:13

My issue was that the cells disappeared completely. This solution helped - however this causes unnecessary reloads. Still it is working now.. thx!

@Hofi 2017-08-24 21:47:11

it causes an infinite loop if calling from the viewController for me

@Cœur 2018-09-17 05:13:56

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.

@Endama 2015-06-19 00:32:35

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

@morph85 2016-01-30 09:02:50

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 2016-01-30 10:05:23

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.

@DrMickeyLauer 2012-11-08 13:26:03

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

@xxtesaxx 2012-10-31 20:06:06

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

@Daniel Wood 2012-11-08 11:00:58

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.

@fatuhoku 2014-08-23 09:38:48

Careful — doing this will cause layout to be run every time you scroll. This can severely impact performance.

@Masa 2012-10-29 17:50:25

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.

@monowerker 2012-10-17 09:28:29

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.

@lindon fox 2012-10-18 01:08:03

Thanks for the extra information @monowerker. I think my problem started when I added the insets (I have added this to the question). I will try your debugging methods and see if it tell me anything. I might try your work around too.

@monowerker 2012-10-18 07:39:26

This is most likely a bug in UICFL/UICL, I'm going to try and get a radar filed when I have the time, here is a discussion with some rdar-numbers you can reference. twitter.com/steipete/status/258323913279410177

Related Questions

Sponsored Content

26 Answered Questions

5 Answered Questions

[SOLVED] UICollectionView in landscape on iPhone X

5 Answered Questions

1 Answered Questions

1 Answered Questions

1 Answered Questions

[SOLVED] UICollectionView cells covering up the scroll indicator

2 Answered Questions

2 Answered Questions

[SOLVED] uicollectionview Loads wierdly

0 Answered Questions

UICollectionView custom flow layout

Sponsored Content