Using [UICollectionView performBatchUpdates:] with a UICollectionViewFlowLayout that has UIDynamics
ios, objective-c, uicollectionview, uicollectionviewlayout, uikit-dynamics
Solution
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.
Problem
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?