Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I've been struggling with a similar situation. </p> <p>In my case I am using UIAttachmentBehaviors, so each UICollectionViewLayoutAttributes item gets its own behavior. So instead of removing items from behaviors, I am removing the appropriate behavior from the dynamic animator.</p> <p>For me, deleting a middle UICollectionViewCell seems to work (no crash), but the app then crashes if I try to delete the last cell.</p> <p>Close inspection of the animator's behaviors (using debug logs) shows that the index paths of the remaining items are indeed off by one past the item that was deleted. Manually resetting them does not by itself fix the issue.</p> <p>The problem seems to be a mismatch between the number of cells in the collection view and the number of items returned by the dynamic animator's -itemsInRect: (all my cells are always visible). </p> <p>I can prevent a crash by removing all behaviors before I delete a cell. But of course this results in an undesired movement of my cells when the attachments go away.</p> <p>What I really needed was a way to reset the items in the dynamic animator without discarding them completely and re-creating them.</p> <p>So, finally, I came up with a mechanism based on storing the behaviors off to the side, re-instatiating a dynamic animator, and re-adding the behaviors.</p> <p>It seems to work well, and can probably be further optimized.</p> <pre><code>- (void)detachItemAtIndexPath:(NSIndexPath *)indexPath completion:(void (^)(void))completion { for (UIAttachmentBehavior *behavior in dynamicAnimator.behaviors) { UICollectionViewLayoutAttributes *thisItem = [[behavior items] firstObject]; if (thisItem.indexPath.row == indexPath.row) { [dynamicAnimator removeBehavior:behavior]; } if (thisItem.indexPath.row &gt; indexPath.row) { thisItem.indexPath = [NSIndexPath indexPathForRow:thisItem.indexPath.row-1 inSection:0]; } } NSArray *tmp = [NSArray arrayWithArray:dynamicAnimator.behaviors]; self.dynamicAnimator = [[UIDynamicAnimator alloc] initWithCollectionViewLayout:self]; for (UIAttachmentBehavior *behavior in tmp) { [dynamicAnimator addBehavior:behavior]; } // custom algorithm to place cells for (UIAttachmentBehavior *behavior in dynamicAnimator.behaviors) { [self setAnchorPoint:behavior]; } [self.collectionView performBatchUpdates:^{ [self.collectionView deleteItemsAtIndexPaths:@[indexPath]]; } completion:^(BOOL finished) { completion(); }]; </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload