Delete cell from UICollectionView without reloading from top [closed]

↘锁芯ラ 提交于 2020-01-09 09:02:43

问题


I am using a CollectionView in my ios app. Each collection cell contains a delete button. By clicking the button the cell should be deleted. After deletion, that space will be filled with below cell (I don't wish to reload the CollectionView and start from top again)

How do I delete a particular cell from UICollectionView with autolayout?


回答1:


UICollectionView will animate and automatically rearrange the cells after deletion.

Delete selected items from collection view

[self.collectionView performBatchUpdates:^{

    NSArray *selectedItemsIndexPaths = [self.collectionView indexPathsForSelectedItems];

    // Delete the items from the data source.
    [self deleteItemsFromDataSourceAtIndexPaths:selectedItemsIndexPaths];

    // Now delete the items from the collection view.
    [self.collectionView deleteItemsAtIndexPaths:selectedItemsIndexPaths]; 

} completion:nil];



// This method is for deleting the selected images from the data source array
-(void)deleteItemsFromDataSourceAtIndexPaths:(NSArray  *)itemPaths
{
    NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
    for (NSIndexPath *itemPath  in itemPaths) {
        [indexSet addIndex:itemPath.row];
    }
    [self.images removeObjectsAtIndexes:indexSet]; // self.images is my data source

}



回答2:


No delegate methods provided to UICollectionViewController as like UITableviewController. We can do it manually by adding a long gesture recognizer to UICollectionView.

 UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self
                                                                                         action:@selector(activateDeletionMode:)];
 longPress.delegate = self;
 [collectionView addGestureRecognizer:longPress];

In longGesture method add button on that particular cell.

- (void)activateDeletionMode:(UILongPressGestureRecognizer *)gr
{
    if (gr.state == UIGestureRecognizerStateBegan) {
        if (!isDeleteActive) {
        NSIndexPath *indexPath = [collectionView indexPathForItemAtPoint:[gr locationInView:collectionView]];
        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        deletedIndexpath = indexPath.row;
        [cell addSubview:deleteButton];
        [deleteButton bringSubviewToFront:collectionView];
        }
     }
 }

In that button action,

- (void)delete:(UIButton *)sender
{
    [self.arrPhotos removeObjectAtIndex:deletedIndexpath];
    [deleteButton removeFromSuperview];
    [collectionView reloadData];
}

I think it can help you.



来源:https://stackoverflow.com/questions/16189682/delete-cell-from-uicollectionview-without-reloading-from-top

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!