UICollectionView flowLayout not wrapping cells cor

2019-01-03 21:12发布

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条回答
Ridiculous、
2楼-- · 2019-01-03 21:27

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.

查看更多
Viruses.
3楼-- · 2019-01-03 21:32

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.

查看更多
看我几分像从前
4楼-- · 2019-01-03 21:33

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.

查看更多
趁早两清
5楼-- · 2019-01-03 21:38

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.

查看更多
祖国的老花朵
6楼-- · 2019-01-03 21:40

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.

查看更多
登录 后发表回答