Search code examples
iosobjective-cuicollectionviewuicollectionviewlayoutuiscrollviewdelegate

UICollectionview custom flow layout delete cell


I have a horizontal UICollectionView that implements UICollectionViewLayout and uses targetContentOffsetForProposedContentOffset for a custom fling/paging functionality. Each cell is nearly the width of the screen with the next cell showing slightly to the right. The functionality works great, but I want to be able to delete the cell at index 0 when the current cell is index 1. I'm currently able to calculate and do this just fine, but upon deleting the index 0 cell it slides to the next cell (old index 2, new 1 (after deleting 0)) because of the current content offset. I'm not sure how I can delete index 0 while maintaining the current layout.

Right now in my delegate I'm doing:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

float cellWidth = self.collectionView.bounds.size.width  - 20;

float currentPage = self.collectionView.contentOffset.x / cellWidth;


if (currentPage == 1) {
    [self remove:0];
}


}


-(void)remove:(int)i {

    [self.collectionView performBatchUpdates:^{
        [self.data removeObjectAtIndex:0];

        NSIndexPath *indexPath =[NSIndexPath indexPathForRow:0 inSection:0];
        [self.collectionView deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];



    } completion:^(BOOL finished) {


    }];
}

So the calculation and deletion works fine, but upon deleting [0], the collection view is scrolled to the next cell..and I'm not sure how to stop it.

I've tried self.collectionview.contentOffset = CGMakePoint(0,0) after the deleting, but the transition is still noticeably buggy. Any ideas on how to approach this problem?


Solution

  • so after a ton of trial and error I was able to resolve the issue. It might be a little hackish but I just wrapped the batch with a uiview animation that has no duration. Basically it overrides the deletion animation

        [UIView animateWithDuration:0 animations:^{
        [self.collectionView performBatchUpdates:^{
            [scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
            [self.data removeObjectAtIndex:0];
            NSIndexPath *indexPath =[NSIndexPath indexPathForRow:0 inSection:0];
            [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
            [self.collectionView.collectionViewLayout invalidateLayout];
        } completion:nil];
    }];