2016-12-06 55 views
0

我有我自己的自定義UICollectionViewLayout,增加了在給定的部分每行自定義標題,當我從那個部分我得到的刪除項目下列崩潰:從UICollectionView一節刪除行似乎並沒有刪除相關頭

***終止應用程序由於未捕獲的異常 'NSInternalInconsistencyException',原因: '的-layoutAttributesForSupplementaryElementOfKind沒有UICollectionViewLayoutAttributes實例:UICollectionElementKindSectionHeader在路徑長度{= 2,路徑= 2 - 0}'

這對我來說毫無意義。我剛剛刪除了2 - 0行,爲什麼它試圖從我的佈局類中請求標題?

這是我刪除行的代碼:

collectionView?.performBatchUpdates({ 
      self.trackControllers.remove(at: index) 
      if self.collectionView?.numberOfItems(inSection: 2) > index { 
       self.collectionView?.deleteItems(at: [IndexPath(row: index, section: 2)]) 
      } 
     }) 

不要緊,如果該部分是刪除後空,或者有其它行,它似乎仍然請求報頭我剛剛刪除的那一行。

回答

3

所以我設法弄清楚了這一點在我自己的。

很顯然,UICollectionView將繼續請求相同的補充視圖,直到刪除動畫結束。爲了解決這個問題,我不得不覆蓋indexPathsToDeleteForSupplementaryView(ofKind elementKind: String) -> [IndexPath]。現在這個愚蠢不向我們提供這些indexPaths已被刪除的任何信息,所以你必須保持對這個自己prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem])

軌道下面是固定我的問題代碼:

fileprivate var deletedIndexPaths = [IndexPath]() 
override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) { 
    deletedIndexPaths.removeAll() 
    super.prepare(forCollectionViewUpdates: updateItems) 

    let newlyDeletedItemsInSection2 = updateItems.filter({ $0.updateAction == .delete }).filter({ $0.indexPathBeforeUpdate?.section == 2 }) 
    let newlyDeletedIndexPaths = newlyDeletedItemsInSection2.flatMap({ $0.indexPathBeforeUpdate }) 
    deletedIndexPaths.append(contentsOf: newlyDeletedIndexPaths) 
} 

override func indexPathsToDeleteForSupplementaryView(ofKind elementKind: String) -> [IndexPath] { 
    return deletedIndexPaths 
} 

override func finalizeCollectionViewUpdates() { 
    deletedIndexPaths.removeAll() 
} 

(注那唯一的部分我有一個有頭是第2節)

+0

謝謝你對「indexPathsToDeleteForSupplementaryView」的提示。引用文檔「例如,當某個部分被刪除時,您可能需要刪除與該部分相關的補充視圖。」當我刪除部分時,我可能會刪除部分標題。我可能... –