I am using a UICollectionView
to display players in various positions on a field. Each cell contains labels showing the player's name and the position name. The locations in the view are determined by a custom layout that reads the position information from the data source... i.e. the location on the field has nothing to do with the index in the data source, as in a flow layout. The cells are also a bit different for various positions... 'cellForItemAtIndexPath' selects from various reuse identifiers depending on the position.
I want the user to be able to swap players in positions. Everything works perfectly as long as I just update the collection view data source and call [self.collectionView reloadData]
. But I want to animate the swap of cells, so the user can see the change. I'm using this code, where the inboundSourceIndex and outboundSourceIndex have been previously set to the items that are swapping:
[self.collectionView performBatchUpdates:^{
[self.collectionView moveItemAtIndexPath:inboundOriginIndex toIndexPath:outboundOriginIndex];
[self.collectionView moveItemAtIndexPath:outboundOriginIndex toIndexPath:inboundOriginIndex];
} completion:nil];
}
[self assignmentsUpdate]; // This method updates the data source for the collection view
[self.collectionView.collectionViewLayout invalidateLayout];
[self.collectionView reloadData];
After I insert the batch update, I get the desired animation of the cells appearing to swap with each other, the player name labels show correctly, and the layout is providing the right frames for the cells (which can vary). But all else is chaos: the position labels don't update, and the cells are not reloading with their correct reuse identifiers--it's like the collectionView isn't really calling cellForItemAtIndexPath
. I've tried changing the order of the data update and the reloadData, to no avail. I can see how moving cells might alter the indexPaths temporarily, but how can the collectionView look wrong after I call invalidateLayout
and reloadData
? Doesn't that build the view from scratch based on the data source?