UICollectionView中的Delete,insert,move

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

- (void)insertItemsAtIndexPaths:(NSArray *)indexPaths;
- (void)deleteItemsAtIndexPaths:(NSArray *)indexPaths;
- (void)reloadItemsAtIndexPaths:(NSArray *)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];
}

摘自网上作者

你可能感兴趣的:(UICollectionView中的Delete,insert,move)