Open cswelin opened 11 years ago
Hey – great question. I've had trouble doing this, too. Can you try the following?
[self.collectionView performBatchUpdates:^{
[self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:self.count inSection:0]]];
self.count++; // or whatever to update your number of cells
} completion:nil];
That should work – let me know either way.
thanks for the response,
It seemed to partially work. I've started the count at 100, if I don't scroll to the bottom it will crash out. But if i'm within 2 rows of the insert it seems to work.
Hmm... that's troubling. Could you zip up your source code and send it to ash@teehanlax.com ? I'd be happy to take a look.
sure, not a problem
OK I've looked into it and the solution is to add new attachment behaviours when new cells are added to the collection view. This is done with the following method, or something similar to it.
-(void)prepareForCollectionViewUpdates:(NSArray *)updateItems
{
[super prepareForCollectionViewUpdates:updateItems];
[updateItems enumerateObjectsUsingBlock:^(UICollectionViewUpdateItem *updateItem, NSUInteger idx, BOOL *stop) {
if (updateItem.updateAction == UICollectionUpdateActionInsert)
{
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:updateItem.indexPathAfterUpdate];
attributes.frame = CGRectMake(10, updateItem.indexPathAfterUpdate.item * 310, 300, 44); // or some other initial frame
UIAttachmentBehavior *springBehaviour = [[UIAttachmentBehavior alloc] initWithItem:attributes attachedToAnchor:attributes.center];
springBehaviour.length = 1.0f;
springBehaviour.damping = 0.8f;
springBehaviour.frequency = 1.0f;
[self.dynamicAnimator addBehavior:springBehaviour];
}
}];
}
There's one problem with it where it seems to cause a crash when you're at the end of the collection view. Does anyone have any ideas on this problem?
It seems to be crashing when adding a behaviour that already exists for that indexPath.
To test this, i've added
if([self.dynamicAnimator layoutAttributesForCellAtIndexPath:updateItem.indexPathAfterUpdate]) return;
just after the if statement and it stops crashing.
Strange that it's trying to add duplicate index paths. Should we close this issue, then?
I have no problems with that, seems to be working smoothly if with the added check.
Made an addition to update the dynamic animator items and the behaviors when cells are inserted/deleted. https://github.com/TeehanLax/UICollectionView-Spring-Demo/pull/12
I've toyed around with the example provided and added a timer to fire
insertItemsAtIndexPaths
every few seconds. Since I want to use a`NSFetchResultsController
later on.Not sure if i'm doing something wrong, but when the insert happens it crashes with
due to
[self.dynamicAnimator layoutAttributesForCellAtIndexPath:indexPath];
returning nil. How do I go about resolving this? I've noticed this same trend on other examples implementing the spring example.