Collection View,with custom layouts, cells misbehave on scrolling - ios

I am trying to create custom tiled layout using UICollectionView.
It renders perfectly as desired in simulator once I run my app.
But the moment I scroll the view and bring it back all the cell's frame changes and the cells get overlapped, leaving spaces, randomly.
I am not able to solve this issue past 2 days.
Here goes the code from my custom layout class.
-(void)prepareLayout{
[self createCellSizeArray];//cellSizeArray holds cell sizes for all the cells(calculated statically)
[self createAttributeArrayOfAll];//attributeArrayOfAll holds attributes for all the cells and also calculates their frames using cellSizeArray
}
-(CGSize)collectionViewContentSize{
return CGSizeMake(768, 1500);//The size is static to check for scrolling, is this creating problems?
}
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewLayoutAttributes * layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
return layoutAttributes;
}
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
NSMutableArray *attArray =[NSMutableArray array];
for (NSInteger i =0; i< attributeArrayOfAll.count; i++) {
UICollectionViewLayoutAttributes * attribute = (UICollectionViewLayoutAttributes*)[attributeArrayOfAll objectAtIndex:i];
if(CGRectIntersectsRect(rect, attribute.frame)){
[attArray addObject:attribute];
}
}
return attArray;
}
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
return YES;
}
Please help, Thanks in advance.
Edit:
In my [self createAttributeArrayOfAll]; I have these lines of code
CGRect frame = CGRectMake(_startNewRowPoint.x, _startNewRowPoint.y, cellSize.width, cellSize.height);
UICollectionViewLayoutAttributes * attribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
attribute.alpha = 1.0;
attribute.frame = frame;
[attributeArrayOfAll addObject:attribute];
While I modified layoutAttributesForItemAtIndexPath:, to look something like this
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewLayoutAttributes * layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
layoutAttributes.frame = ((UICollectionViewLayoutAttributes*)[attributeArrayOfAll objectAtIndex:indexPath.item]).frame;
return layoutAttributes;
}
Moreover, the method layoutAttributesForItemAtIndexPath: never gets called implicitly. I even tried this:
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
NSMutableArray *attArray =[NSMutableArray arrayWithCapacity:attributeArrayOfAll.count];
for (NSInteger i =0; i< attributeArrayOfAll.count; i++) {
UICollectionViewLayoutAttributes * attribute = (UICollectionViewLayoutAttributes*)[attributeArrayOfAll objectAtIndex:i];
if(CGRectIntersectsRect(rect, attribute.frame)){
[attArray insertObject:[self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]] atIndex:i];
}
}
return attArray;
}
But still the result is the same distorted set of cells on scrolling.
I worked with 5 cells, first time it renders correctly, on scrolling away and then bringing it back in visible rect it gets distorted, if i scroll away again and bring it back in visible rect it renders correctly. However, when I do this with around 400 cells, once i scroll it never renders correctly. Even on reloading collection view, The cells gets distort. Please help.

Your layoutAttributesForItemAtIndexPath: method is not setting any properties of the layoutAttributes object before returning it. It needs to set frame (or center and size).

So finally managed a workaround!!! dequeue each cell with an unique Cell Identifier in cellForRow:
[self.summaryView registerClass:[BFSSummaryViewCell class] forCellWithReuseIdentifier:[NSString stringWithFormat:#"%#%d",CellIdentifier,indexPath.row]];
UICollectionViewCell *collectionCell = [collectionView dequeueReusableCellWithReuseIdentifier:[NSString stringWithFormat:#"%#%d",CellIdentifier,indexPath.row] forIndexPath:indexPath];
These two lines inside cellForRow worked for me, however with my collection view having around 1000 cells it increases the size of my application considerably. Lets hope apple fixes this bug asap.

Related

Create a view using collection view in ios

I am trying to create a view similar to the attached image below. there is a variable sized width. I have marked text as black as there is a copyright issue.
Can anyone please look into the same and put some code so that it can help me somewhere.
Do I need to implement Custom Collection View Layout?
Please help me.
This is response to your comment you need to add 3 extra lines of code in SGSStaggeredFlowLayout
NSArray* arr = [super layoutAttributesForElementsInRect:rect];
// THIS CODE SEPARATES INTO ROWS
NSMutableArray* rows = [NSMutableArray array];
NSMutableArray* currentRow = nil;
NSInteger currentIndex = 0;
BOOL nextIsNewRow = YES;
for (UICollectionViewLayoutAttributes* atts in arr) {
if (nextIsNewRow) {
nextIsNewRow = NO;
if (currentRow) {
[rows addObject:currentRow];
}
currentRow = [NSMutableArray array];
}
if (arr.count > currentIndex+1) {
UICollectionViewLayoutAttributes* nextAtts = arr[currentIndex+1];
if (nextAtts.frame.origin.y > atts.frame.origin.y) {
nextIsNewRow = YES;
}
}
[currentRow addObject:atts];
currentIndex++;
}
if (![rows containsObject:currentRow]) {
[rows addObject:currentRow];
}
It works like charm :)
You can set size for every item by impelmenting
UICollectionViewDelegateFlowLayout protocol, and calculate item width using even/odd formula.
-(CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)collectionView.collectionViewLayout;
NSInteger itemsPerRow = 0;
NSInteger contentSizeWidth = 0;
NSInteger num = indexPath.row;
if (num % 2)
{// odd
itemsPerRow = 2;
}
else {
// even
itemsPerRow = 3;
}
contentSizeWidth = collectionView.frame.size.width- (flowLayout.minimumInteritemSpacing*(itemsPerRow-1))-flowLayout.sectionInset.left-flowLayout.sectionInset.right;
return CGSizeMake(contentSizeWidth/itemsPerRow, 100);
}
if you are trying to do this without any framework, you need to develop your own algroithm to calculate the width of each cell.
first, you need to calculate the width of text plus margin maybe border as well.
Second, calculate how many items are gonna be placed in given row. try to add 3 togther , if the total width excess the uicollection width, it means the third text should go to the next cell. if it is less than the collection width,it means you can add try to the 4th text.
third, caculate the width of each cell in each line base on how many cells are gonna placed on that line and their own width.
changing the uicollectionview width should not be diffculty since collectionviewcells are darw from left to right then top to bottom.

UICollectionViewFlowLayout performance for Text Grid

I have an iOS 7 app using Storyboards that has the following structure:
UITabBarController->UINavgiationController->UICollectionViewController
I use a custom subclass of UICollectionViewFlowLayout to layout the grid. Each cell contains a single UILabel.
I am trying to render a 5 column grid in the UICVC. There can be upwards of 800 rows (sections, as one row per section). I've based this loosely on Erica Sadun's example code from her iOS book.
The cells all have specific, set widths (2 different widths used). All cells have the same height. The grid is wider than the physical display, and so scrolls horizontally and vertically.
It's all working fine, but performance has been very poor for more than about 30 rows. The problem comes when trying to calculate the custom layout, specifically in the following method:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *attribs = [super layoutAttributesForElementsInRect:rect];
NSMutableArray *attributes = [NSMutableArray array];
[attribs enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes *currentLayout, NSUInteger idx, BOOL *stop)
{
NSString *layoutItemKey = [NSString stringWithFormat:#"%ld:%ld", (long)currentLayout.indexPath.section, (long)currentLayout.indexPath.item];
UICollectionViewLayoutAttributes *newLayout = [self.cachedLayoutAttributes objectForKey:layoutItemKey];
if (nil == newLayout)
{
newLayout = [self layoutAttributesForItemAtIndexPath:currentLayout.indexPath];
long section = currentLayout.indexPath.section;
long item = currentLayout.indexPath.item;
NSString *layoutItemKey = [NSString stringWithFormat:#"%ld:%ld", (long)section, (long)item];
[self.cachedLayoutAttributes setObject:newLayout forKey:layoutItemKey];
}
[attributes addObject:newLayout];
}];
return attributes;
}
The main delay here seems to come from a call to the iOS method:
layoutAttributesForCellWithIndexPath:(NSIndexPath *)indexPath;
which is inside the layoutAttributesForItemAtIndexPath method:
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
CGSize thisItemSize = [self sizeForItemAtIndexPath:indexPath];
CGFloat verticalOffset = [self verticalInsetForItemAtIndexPath:indexPath];
CGFloat horizontalOffset = [self horizontalInsetForItemAtIndexPath:indexPath];
if (self.scrollDirection == UICollectionViewScrollDirectionVertical)
attributes.frame = CGRectMake(horizontalOffset, verticalOffset, thisItemSize.width, thisItemSize.height);
else
attributes.frame = CGRectMake(verticalOffset, horizontalOffset, thisItemSize.width, thisItemSize.height);
return attributes;
}
Scrolling works fine to a point, then freezes for about 1.5 seconds while the next block of layout is calculated (always seems to be about 165 cells). As I'm caching everything, the next time the user scrolls performance is fine.
If I leave the cell widths to the UICollectionViewFlowLayout default everything flies, with no pauses.
To try to speed things up I have:
Ensured all views are opaque
Set the deceleration rate of the CollectionView to FAST
Made - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds return NO
I cache any UICollectionViewLayoutAttributes calculated
I cache the first 50 rows on initialisation. There's no noticeable lag doing this, and it allows the initial scroll performance to be a bit better than it would have been
I've run out of ideas for squeezing more performance out of the UICollectionViewFlowLayout.
Can anyone suggest how I can improve the code?
Thanks
Darren.
I've found a solution to the problem, and while it's not a complete answer to UICollectionView performance problems, it meets my needs.
I'm rendering a text grid. The rows are all the same height, the widths of the fields are always the same, and the overall width of a row is always the same.
Erica Sadun's code allows for variable height text cells, for text wrapping I assume. Because of that the layout needs to be calculated for each cell and row. For a grid with more than 100 cells the amount of time required is too long (on my iPhone 4S).
What I've done is to remove all the height and width calculation code, and replace it with fixed values I calculated manually.
This removes the bottleneck, and now I can render a grid with a few thousand cells without any noticeable lag.

Subclassing UICollectionViewFlowLayout cause blank cells

Using UICollectionViewFlowLayout ,i have 2 columns- collection view that works great .
Problem have started when i needed a constant distance between cells at the same row, when they have a dynamic height .
So , i have subclass UICollectionViewFlowLayout as everybody do, but what it did, is to eliminate the next cells to be loaded to screen, so while scrolling i have blank spaces ,without cells, and than they are suddenly loaded in late . looks like
1 2
3 4
6
8
10
Than, 5-7-10 suddenly appears late. seems that the subclass change the delegate method that creates the cells, and its now not being called at time, to load the next cells .
Whats wrong with it ? i am struggling 3 days with no results.
The subclass method that suppose to make the spacing equal(and cause the problem)
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewLayoutAttributes* currentItemAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];
if (indexPath.item < numColumns)
{
CGRect f = currentItemAttributes.frame;
f.origin.y = 0;
currentItemAttributes.frame = f;
return currentItemAttributes;
}
NSIndexPath* ipPrev = [NSIndexPath indexPathForItem:indexPath.item-numColumns inSection:indexPath.section];
CGRect fPrev = [self layoutAttributesForItemAtIndexPath:ipPrev].frame;
CGFloat YPointNew = fPrev.origin.y + fPrev.size.height + 10;
CGRect f = currentItemAttributes.frame;
f.origin.y = YPointNew;
currentItemAttributes.frame = f;
return currentItemAttributes;
}
EDIT !
After 3 days ,i have manage to change something that solve the problem, but makes no sense.
I have changed the content height of the collection view to be 6 times the screen size! this solved the problem. I think i am doing something wrong with setting the content side of flow and collection:
TopAlignedCollectionViewFlowLayout *layout=[[TopAlignedCollectionViewFlowLayout alloc] init];
CGRect size=CGRectMake( ([UIScreen mainScreen].bounds.size.width-collectionWidth)/2,
upperView.frame.size.height, collectionWidth, 6.5*([UIScreen mainScreen].bounds.size.height-upperLineMargin));
self.GridView=[[UICollectionView alloc] initWithFrame:size collectionViewLayout:layout];
[self.GridView registerClass:[GridCell class] forCellWithReuseIdentifier:#"Cell"];
Only now, he loads all cells at time. problem is that now i can't get to the end of the collection.

UICollectionView flowLayout not wrapping cells correctly

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.
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.
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
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 }
}
}
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.
I have added a bug report to Apple. What works for me is to set bottom sectionInset to a value less than top inset.
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.
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.
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
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.
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 😊
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]
}
}

UICollectionView Performance Problems on performBatchUpdates

We are trying to set up a UICollectionView with a custom layout. The content of each CollectionViewCell will be an image. Over all there will be several thousand images and about 140-150 being visible at one certain time. On an action event potentially all cells will be reorganized in position and size. The goal is to animate all the moving events currently using the performBatchUpdates method. This causes a huge delay time before everything gets animated.
This far we found out that internally the method layoutAttributesForItemAtIndexPath is called for every single cell (several thousand in total). Additionally, the method cellForItemAtIndexPath is called for more cells than can actually be displayed on the screen.
Are there any possibilities to enhance the performance of the animation?
The default UICollectionViewFlowLayout can't really offer the kind of design we want to realize in the app. Here's some of our code:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
RPDataModel *dm = [RPDataModel sharedInstance]; //Singleton holding some global information
NSArray *plistArray = dm.plistArray; //Array containing the contents of the cells
NSDictionary *dic = plistArray[[indexPath item]];
RPCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"CELL" forIndexPath:indexPath];
cell.label.text = [NSString stringWithFormat:#"%#",dic[#"name"]];
cell.layer.borderColor = nil;
cell.layer.borderWidth = 0.0f;
[cell loadAndSetImageInBackgroundWithLocalFilePath:dic[#"path"]]; //custom method realizing asynchronous loading of the image inside of each cell
return cell;
}
The layoutAttributesForElementsInRect iterates over all elements setting layoutAttributes for allthe elements within the rect. The for-statement breaks on the first cell being past the borders defined by the bottom-right corner of the rect:
-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
NSMutableArray* attributes = [NSMutableArray array];
RPDataModel *dm = [RPDataModel sharedInstance];
for (int i = 0; i < dm.cellCount; i++) {
CGRect cellRect = [self.rp getCell:i]; //self.rp = custom object offering methods to get information about cells; the getCell method returns the rect of a single cell
if (CGRectIntersectsRect(rect, cellRect)) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:[dm.relevanceArray[i][#"product"] intValue] inSection:0];
UICollectionViewLayoutAttributes *attribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
attribute.size = cellRect.size;
attribute.center = CGPointMake(cellRect.origin.x + attribute.size.width / 2, cellRect.origin.y + attribute.size.height / 2);
[attributes addObject:attribute];
} else if (cellRect.origin.x > rect.origin.x + rect.size.width && cellRect.origin.y > rect.origin.y + rect.size.height) {
break;
}
}
return attributes;
}
On Layout changes the results are pretty much the same no matter if the number of cells being defined in the layoutAttributesForElementsInRect is limited or not .. Either the system gets the layout attributes for all cells in there if it isn't limited or it calls the layoutAttributesForElementAtIndexPath method for all the missing cells if it is limited. Overall the attributes for every single cell is being used somehow.
-(UICollectionViewLayoutAttributes*)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
RPDataModel *dm = [RPDataModel sharedInstance];
UICollectionViewLayoutAttributes *attribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
CGRect cellRect = [self.rp getCell:[dm.indexDictionary[#(indexPath.item)] intValue]];
attribute.size = cellRect.size;
attribute.center = CGPointMake(cellRect.origin.x + attribute.size.width / 2, cellRect.origin.y + attribute.size.height / 2);
return attribute;
}
Without seeing code, my guess is that your layoutAttributesForElementsInRect method is iterating through all of the items in your collection, and that is, in turn, what is causing the other methods to get over-called. layoutAttributesForElementsInRect is giving you a hint - that is, the CGRect it is passing to you - about which items you need to call layoutAttributesForItemAtIndexPath for, in terms of what is on the screen.
So that may be part of the performance issue - that is, tuning your custom layout so it is being smart about which items it is updating.
The other issues pertain to animation performance in general. One thing to watch out for is if there is any sort of compositing going on - make sure your images are opaque. Another thing is if you're using shadows on your image, those can be expensive to animate. One way to improve the animation performance of shadows is set the shadowPath value when the image is resized - if you do have shadows, let me know and post some code for doing that.
This appears to be caused by trying to add cells to sections which have header views but no cells already in them.
The error message is monumentally unhelpful, and it took several hours of effort to trace it down.

Resources