iOS15 UICollectionView自定义布局,插入项目后,viewForSupplementaryElementOfKind总是重新创建一个新标题

hig*_*ore 1 ios uicollectionview uicollectionviewlayout ios15

// viewdidload register
[self.collectionView registerClass:[TestHeaderCollectionReusableView class]
            forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                   withReuseIdentifier:NSStringFromClass(NEHeaderCollectionReusableView.class)];

// viewForSupplementaryElementOfKind called
TestHeaderCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                                  withReuseIdentifier:NSStringFromClass(TestHeaderCollectionReusableView.class)
                                                                                         forIndexPath:indexPath];

Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在 iOS15 上,插入一个项目后

- (void)insertItem {
    [self.dataSourece.firstObject insertObject:@{
        @"title" : @"ins1"
    } atIndex:0];
    NSIndexPath * path= [NSIndexPath indexPathForItem:0 inSection:0];
    [self.collectionView insertItemsAtIndexPaths:@[path]];
}
Run Code Online (Sandbox Code Playgroud)

在我插入项目后,它总是会在第一次重新创建 TestHeaderCollectionReusableView 。但在 iOS14 上,它将从缓存中进行杜克。

不知道为什么。

小智 6

修复了 iOS 15 中的 UICollectionElementKindSectionHeader 崩溃

在我的 collectionView 中,我只使用标题。它适用于 iOS 14,但在 iOS 15 中崩溃。

应用程序在 AppDelegate 上崩溃,我收到此错误

*** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“从 -collectionView:viewForSupplementaryElementOfKind:atIndexPath: 返回的视图与它所使用的元素种类不匹配。当请求元素类型“UICollectionElementKindSectionHeader”的视图时,数据源使为元素类型“MyCollectionReusableView”注册的视图出队。

注册头

    collectionView.register(UINib(nibName: "MyCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "MyCollectionReusableView")
Run Code Online (Sandbox Code Playgroud)

然后在 UICollectionViewDataSource 方法中

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "MyCollectionReusableView", for: indexPath) as! MyCollectionReusableView
        headerView.backgroundColor = .red
        // Configure header view .....
        return headerView
    }
Run Code Online (Sandbox Code Playgroud)

将 forSupplementaryViewOfKind: 和 ofKind: 从“MyCollectionReusableView”替换为 UICollectionView.elementKindSectionHeader

这对我有用。