删除单元格时,执行 deleteItemsAtIndexPaths 的方法以达到动画过渡的效果;然而使用过程中可能会有这个报错:

1
Assertion failure in -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3512.30.14/UICollectionView.m:4324

个人猜想:

UICollectionView 在执行 deleteItemsAtIndexPaths 时会做一个断言:删除后,对应 numberOfItemsInSection 的值要比删除前少 indexPaths.count

在下面的代码中 numberOfItemsInSection 返回值是 MIN(_assets.count + 1, MAX_NUM_OF_PHOTO)

_assets.count == MAX_NUM_OF_PHOTO 的情况下,删除前后 numberOfItemsInSection 均为 MAX_NUM_OF_PHOTO

这也是 [_assets removeObjectAtIndex:indexPath.row]; 必须在 [_gridView deleteItemsAtIndexPaths:@[indexPath]]; 之前执行的原因。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
- (void)removePickImageCell:(PickImageCell *)cell
{
NSIndexPath *indexPath = [_gridView indexPathForCell:cell];
if(_assets.count == MAX_NUM_OF_PHOTO)
{
[_assets removeObjectAtIndex:indexPath.row];
[_gridView reloadData];
}
else
{
// 动画过渡
[_assets removeObjectAtIndex:indexPath.row];
[_gridView deleteItemsAtIndexPaths:@[indexPath]];
}
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return MIN(_assets.count + 1, MAX_NUM_OF_PHOTO);
}