2017-08-06 91 views
4

UICollectionview加載了簡單的單元格,並且有一個簡單的int變量用於計算該部分中的項目數。UICollectionView在reloadData上崩潰

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return viewCount 
} 

當viewCount的值(最初爲45)更改爲較低的數字(例如12)時,應用程序崩潰。

這是錯誤信息更新項目數:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView received layout attributes for a cell with an index path that does not exist: <NSIndexPath: 0x17402fbe0> {length = 2, path = 0 - 12}' 

我試着重裝數據緩存失效以及表示here。這沒有幫助。我也嘗試在無效緩存之前重新加載indexSet。這也沒有幫助。

func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
     if textField == countTextField { 
      viewCount = Int(textField.text!)! 
      textField.resignFirstResponder() 
      let indexSet = IndexSet(integer: 0) 

//   collectionView.reloadSections(indexSet) 
      collectionView.reloadData() 
      collectionView.collectionViewLayout.invalidateLayout() 
     } 

     return true 
    } 

我用2定製UICollectinViewLayout和我還設置shouldInvalidateLayout是真實的。 有什麼幫助嗎?

更新

func numberOfSections(in collectionView: UICollectionView) -> Int { 
     return 1 
    } 

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DemoCell", for: indexPath) as! DemoCollectionViewCell 
     cell.indexLabel.text = "\(indexPath.item + 1)" 

     return cell 
    } 

    @IBAction func showLayout1(_ sender: Any) { 
     currentLayout = DemoACollectionViewLayout() 
     animateLayout() 
    } 

    @IBAction func showLayout2(_ sender: Any) { 
     currentLayout = DemoBCollectionViewLayout() 
     animateLayout() 
    } 

    func animateLayout() { 
     UIView.animate(withDuration: 0.3) { [weak self] value in 
      guard let `self` = self else { return } 
      self.collectionView.collectionViewLayout.invalidateLayout() 
      self.collectionView.collectionViewLayout = self.currentLayout! 
     } 
    } 

這裏是sample項目。

更新: 我已經更新爲使用的dataObject時重新加載UICollectionView但UICollectionViewLayout緩存中,當我失效沒有被清除。

+0

請發表您的其他收藏視圖委託方法 – BJHStudios

+0

爲什麼不使用數組填充表? –

+0

這只是一個演示佈局,並不需要datasource.Just空單元格跟蹤索引的標籤 –

回答

3

當collectionView的項目數已更改時,必須清除緩存。

guard let views = collectionView?.numberOfItems(inSection: 0) 
      else { 
    cache.removeAll() 
    return 
} 

if views != cache.count { 
    cache.removeAll() 
} 

if cache.isEmpty { 
    //Layout attributes 
} 
相關問題