【问题标题】:UICollectionView crashes when column count changes列数更改时 UICollectionView 崩溃
【发布时间】:2017-02-21 04:53:02
【问题描述】:

我有一个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() 使集合视图无效也没有帮助。我一直在花费几个小时仍然没有运气。提前致谢。

【问题讨论】:

  • 拥有self.collectionView.collectionViewLayout.invalidateLayout() 应该可以帮助您。奇怪的是它没有工作。让我们拭目以待社区的答案。
  • 崩溃究竟发生在哪里?什么是崩溃输出/错误?

标签: ios swift uicollectionview uicollectionviewlayout


【解决方案1】:

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

它应该按以下顺序进行。试着告诉我。

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

换句话说,以下应该是使collectionview失效时的顺序

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

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    相关资源
    最近更新 更多