补充意见未被删除

我正在构建自定义布局集合视图。 我的collections中每个项目有2个补充视图。 当我想删除一个项目时,我的layoutAttributesForSupplementaryViewOfKind:atIndexPath:实现将使用不再存在的补充视图进行调用。 这意味着我得到的索引路径没有正确映射到我的数据源,而且我遇到了一个越​​界问题。

我做了一些日志记录,第一个例子中的内容是当我们开始使用某些数据时,或者每当我们将项目插入到集合视图中时,计算集合视图的正确和逻辑方式。

第二组日志是在删除我的数据源中的对象后删除deleteItemsAtIndexPaths:

我的layoutAttributesForElementsInRect:看起来像这样:

 - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect { NSMutableArray* attributes = [NSMutableArray array]; for (NSInteger i = 0 ; i < [self.myData count]; i++) { NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0]; NSLog(@"%@ indexPath.row:%d", NSStringFromSelector(_cmd), indexPath.row); UICollectionViewLayoutAttributes *att = [self layoutAttributesForItemAtIndexPath:indexPath]; [attributes addObject:att]; UICollectionViewLayoutAttributes *att_supp = [self layoutAttributesForSupplementaryViewOfKind:@"one_kind" atIndexPath:indexPath]; [attributes addObject:att_supp]; UICollectionViewLayoutAttributes *linesAttr = [self layoutAttributesForSupplementaryViewOfKind:@"another_kind" atIndexPath:indexPath]; [attributes addObject:linesAttr]; } return attributes; } 

初始日志(正确和逻辑):

 MyApp[18546:70b] layoutAttributesForElementsInRect: indexPath.row:0 MyApp[18546:70b] layoutAttributesForSupplementaryViewOfKind:atIndexPath: indexPath.row:0 MyApp[18546:70b] layoutAttributesForSupplementaryViewOfKind:atIndexPath: indexPath.row:0 MyApp[18546:70b] layoutAttributesForElementsInRect: indexPath.row:1 MyApp[18546:70b] layoutAttributesForSupplementaryViewOfKind:atIndexPath: indexPath.row:1 MyApp[18546:70b] layoutAttributesForSupplementaryViewOfKind:atIndexPath: indexPath.row:1 MyApp[18546:70b] layoutAttributesForElementsInRect: indexPath.row:2 MyApp[18546:70b] layoutAttributesForSupplementaryViewOfKind:atIndexPath: indexPath.row:2 MyApp[18546:70b] layoutAttributesForSupplementaryViewOfKind:atIndexPath: indexPath.row:2 

删除项目后:

 MyApp[18633:70b] layoutAttributesForElementsInRect: indexPath.row:0 MyApp[18633:70b] layoutAttributesForSupplementaryViewOfKind:atIndexPath: indexPath.row:0 MyApp[18633:70b] layoutAttributesForSupplementaryViewOfKind:atIndexPath: indexPath.row:0 MyApp[18633:70b] layoutAttributesForElementsInRect: indexPath.row:1 MyApp[18633:70b] layoutAttributesForSupplementaryViewOfKind:atIndexPath: indexPath.row:1 MyApp[18633:70b] layoutAttributesForSupplementaryViewOfKind:atIndexPath: indexPath.row:1 MyApp[18633:70b] layoutAttributesForSupplementaryViewOfKind:atIndexPath: indexPath.row:2 

正如您所见,通过绕过layoutAttributesForElementsInRect:调用layoutAttributesForElementsInRect:

有谁知道可能出了什么问题?

我有同样的问题。 我的布局为集合视图中的每个项目使用一个补充视图。 我通过几个步骤解决了这个问题。

首先,在- prepareForCollectionViewUpdates: ,我枚举更新并确定哪些项目正在消失。 我缓存那组索引路径。

然后布局将调用- indexPathsToDeleteForSupplementaryViewOfKind: . 我刚刚从上面返回了缓存的结果。

最后,在- finalizeCollectionViewUpdates ,我清除了缓存。 我想这一步是可选的。

我也是这样做的- indexPathsToInsertForSupplementaryViewOfKind:为了保持一致,虽然没有它就可以正常工作。