错误:UICollectionView收到了在Swift中不存在具有索引路径的单元格的布局属性

时间:2018-11-13 07:15:29

标签: ios swift uicollectionview

我 “ https://www.raywenderlich.com/392-uicollectionview-custom-layout-tutorial-pinterest” 创建一个自定义UICollectionView。 (调整单元格高度)

如果我向上滚动,该单元将继续添加,并从上到下滚动以刷新。

运行应用程序并最初增长Cells时没有问题。 但是,刷新或重新排列单元格数量时始终会出错。

错误:

  

***-[UICollectionViewData validateLayoutInRect:],/ BuildRoot / Library / Caches / com.apple.xbs / Sources / UIKitCore / UIKit-3698.93.8 / UICollectionViewData.m:447

中的断言失败      

***由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'UICollectionView接收到索引路径不存在的单元格的布局属性:

因此, “ iOS 10 bug: UICollectionView received layout attributes for a cell with an index path that does not exist” 并尝试解决错误。

在下面的行

self.artCollectionView.reloadData () 

我尝试添加

self.artCollectionView.collectionViewLayout.invalidateLayout () 

但未解决。

此外,我不知道在哪里运行

cache.removeAll ()
在prepare()部分中

。 (PinterestLayout.swift中有一个prepare()函数)

解决错误的正确方法是什么?

4 个答案:

答案 0 :(得分:5)

prepare中应有PinterestLayout.swift函数,因为它是用于自定义collectionView的唯一布局。

PinterestLayout.swift文件的第76行。

尝试

override public func prepare() {
    cache.removeAll()
    if cache.isEmpty {
       .....
    }
}

答案 1 :(得分:1)

extension UICollectionView{
   func refreshLayout() {
        let oldLayout = collectionViewLayout as! UICollectionViewFlowLayout
        let newLayout = UICollectionViewFlowLayout()
        newLayout.estimatedItemSize = oldLayout.estimatedItemSize
        newLayout.footerReferenceSize = oldLayout.footerReferenceSize
        newLayout.headerReferenceSize = oldLayout.headerReferenceSize
        newLayout.itemSize = oldLayout.itemSize
        newLayout.minimumInteritemSpacing = oldLayout.minimumInteritemSpacing
        newLayout.minimumLineSpacing = oldLayout.minimumLineSpacing
        newLayout.scrollDirection = oldLayout.scrollDirection
        newLayout.sectionFootersPinToVisibleBounds = oldLayout.sectionFootersPinToVisibleBounds
        newLayout.sectionHeadersPinToVisibleBounds = oldLayout.sectionHeadersPinToVisibleBounds
        newLayout.sectionInset = oldLayout.sectionInset
        newLayout.sectionInsetReference = oldLayout.sectionInsetReference
        collectionViewLayout = newLayout
    }
  }

然后致电:

YourCollectionView.refreshLayout()
YourCollectionView.reloadData()

快乐编码!

答案 2 :(得分:1)

当我不小心将col​​lectionView单元格的高度设置为0时收到此错误。请确保高度(或任何尺寸)大于0!确保它始终大于0可以解决我的问题。

答案 3 :(得分:1)

在我的情况下,由于我对三个collectionView使用相同的layout(UICollectionViewFLowLayout)对象,因此,使用不同的布局对象(创建三个相同的新布局)更改为每个collectionView,此崩溃将消失。

我遇到这个问题是因为我对三个collectionView使用了同一个布局,导致重新加载的时候出错,改成每个collectionView使用不同的布局对象就没事了。