11

Okay so basic overview. I have a UICollectionView that I needs to support adding and removing item through the performBatchUpdates: method. If I use a standard UICollectionViewFlowLayout, it works fine.

However, when I try to use a UICollectionViewFlowLayout that is powered by a UIDynamicAnimator, then I get a crash as soon as I call performBatchChanges.

On my custom UICollectionViewFlowLayout class, the prepareForCollectionViewUpdates: method never gets called. The custom UICollectionViewFlowLayout that I am using is based off of this sample.

The console output after the crash is...

*** Assertion failure in -[UICollectionViewData layoutAttributesForItemAtIndexPath:], /SourceCache/UIKit/UIKit-2903.23/UICollectionViewData.m:581
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForItemAtIndexPath: <NSIndexPath: 0xc000000000028096> {length = 2, path = 2 - 5}'
*** First throw call stack:
libc++abi.dylib: terminating with uncaught exception of type NSException

Any ideas?

Ross Kimes
  • 1,234
  • 1
  • 12
  • 34
  • did you find a fix for this? The answer below covers when cell is not visible, but this is happening to me when the cell is visible, and it's random crash happening in prod that I cannot reproduce myself. I don't even use a UIDynamicAnimator – aryaxt Mar 29 '16 at 00:28
  • The answer blow worked for me, it was the correct fix for me. – Ross Kimes Mar 30 '16 at 18:17

1 Answers1

13

try

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *layoutAttributes = [self.dynamicAnimator layoutAttributesForCellAtIndexPath:indexPath];
    if(!layoutAttributes) {
        layoutAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];
    }
    return layoutAttributes;
}

when you execute performBatchUpdates, [self.dynamicAnimator layoutAttributesForCellAtIndexPath: returns nil if cell which will be created by update is not visible. So just returns super(perhaps UICollectionViewFlowLayout)' s layoutAttributes for now. And when the cell about to be displayed, UIDynamicAnimator will do the job for you.

akira108
  • 330
  • 3
  • 18