UICollectionView中的Delete,insert,move

UICollectionView的删除和插入(insert, delete),都会自动调用reloadData;因此需要在调用如下方法前先处理一下datasource(数据源)

- (void)insertItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;
- (void)deleteItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;
- (void)reloadItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;

eg:

 [self.userInfos insertObject:info atIndex:0];
  [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]]];

但有时又需要注意一些情况,reloadData的官方提示是:

You should not call this method in the middle of animation blocks where items are being inserted or deleted. Insertions and deletions automatically cause the table’s data to be updated appropriately.
你不能在插入或删除的动画block中调用此方法,另外,插入和删除操作会自动更新table的数据;

再有一点有时我们删除或插入前尽可能先判断一下;因为这些插入和删除是线程不安全的,

删除时
[self.infos removeLastObject];
if ([self.collectionView numberOfItemsInSection:0] == self.infos.count) {
      [self.collectionView reloadData];
}else{
      [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:self.infos.count-1 inSection:0]]];
 }
添加时
[self.infos insertObject:info atIndex:0];

if (self.infos.count == 1 || [self.collectionView numberOfItemsInSection:0] == self.infos.count) {
        [self.collectionView reloadData];
}else{
        [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:0 inSection:0]]];
}

另:这里附上一种可以实现长按删除cell的方法:

- (void)deleteAddress:(UILongPressGestureRecognizer*)longPress{
    CGPoint pt = [longPress locationInView:self.collectionView];
  
    //主要是此方法可以根据point拿到当前点击的cell的index;
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:pt];
   
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"删除地址" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        LTAddressListModel *model = self.dataArray[indexPath.row];
        [self deletMyAddressWithParmas:@{@"ids":model.ID}];
        [self.dataArray removeObjectAtIndex:indexPath.row];
        [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertControl addAction:action];
    [alertControl addAction:cancelAction];

    [self presentViewController:alertControl animated:NO completion:nil];
}

摘自网上作者

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容