列数更改时 UICollectionView 崩溃

UICollectionView crashes when column count changes

我有一个 UICollectionview 并且列数随机变化。每次列数更改时,我都会调用以下函数。

func setTheCollectionViewSize(){



    if self.activeLockerList.count > 0 {
        self.btnLockerDropdown.setTitle("Lockers Set \(self.activeLockerList[0].lockerId)", for: UIControlState.normal)
    }

    screenSize = UIScreen.main.bounds
    screenWidth = screenSize.width
    screenHeight = screenSize.height


    //if the collection view layout is not invalidated then the app will crash


    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.minimumInteritemSpacing = 0
    layout.minimumLineSpacing = 0

    //setting the collectionview size so there will be no white lines in the drawn boxes
    var appropriateScreenWidth = Int(self.screenWidth)
    while appropriateScreenWidth % Int(self.numberOfLockersPerColumn) != 0 {
        appropriateScreenWidth = appropriateScreenWidth - 1
    }

    let itemWidth : CGFloat = CGFloat(appropriateScreenWidth) / self.numberOfLockersPerColumn
    collectionViewWidthLocal.constant = CGFloat(appropriateScreenWidth)
    layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
    print(self.numberOfLockersPerColumn)
    print(screenWidth)

    layout.minimumInteritemSpacing = 0
    layout.minimumLineSpacing = 0
    layout.sectionInset = UIEdgeInsets(top: 10.0, left: 0, bottom: 10.0, right: 0)

    self.collectionView.collectionViewLayout.invalidateLayout()

    self.collectionView.setCollectionViewLayout(layout, animated: false)

}

当每行的单元格计数增加时,它工作正常。但是,当计数减少时,应用程序会在 self.collectionView.setCollectionViewLayout(layout, animated: false)

行崩溃

如您所见,使用 self.collectionView.collectionViewLayout.invalidateLayout() 使 collectionview 无效也没有帮助。我一直在花费数小时,但仍然没有运气。提前致谢。

您是在 collectionView.reloadData() 之前还是之后调用了 setTheCollectionViewSize() 函数?

应该按以下顺序进行。试试让我知道。

self.collectionView.reloadData()
self.setTheCollectionViewSize()

也就是说下面应该是使collectionview失效的顺序

self.collectionView.reloadData()
self.collectionView.collectionViewLayout.invalidateLayout()

希望对您有所帮助。