2017-02-21 53 views
1

我有一個UICollectionview,列數隨機變化。每當列數發生變化時,我都會調用以下函數。當列數發生變化時,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也沒有幫助。我已經花了幾個小時,但仍然沒有運氣。提前致謝。

+0

有'self.collectionView.collectionViewLayout.invalidateLayout()'應該幫助你。奇怪它沒有用。讓我們拭目以待來自社區的答案。 –

+0

崩潰發生在哪裏?什麼是崩潰輸出/錯誤? – shallowThought

回答

2

您是否在collectionView.reloadData()之前或之後調用setTheCollectionViewSize()函數?

它應該按以下順序進行。試着讓我知道。

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

換句話說以下應該是爲了無效的CollectionView

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

希望它可以幫助你來的時候。