-->

Crashing while collection view cell deletion becau

2019-02-20 02:31发布

问题:

My data source is a 2-dimensional array because I have emojis divided into sections.

eg. [[a,b,c,d],[e,f,g],[h,j,k,l,m]]

My cell deletion code -

func deleteEmoji(at indexPath: IndexPath) {

    // Get the bad emoji
    let emojiToBeDeleted = emojisArray[indexPath.section][indexPath.row]

    // Delete the emoji from datasource and collection view
    emojisArray[indexPath.section].remove(at: indexPath.row)
    stickerCollectionView.deleteItems(at: [indexPath])

    // Delete the section from datasource and collection view as its emoji count is zero
    if emojisArray[indexPath.section].count == 0 {
        emojisArray.remove(at: indexPath.section)
        stickerCollectionView.deleteSections(IndexSet(integer: indexPath.section)) // Crashing here :(
        sectionCollectionView.reloadData()
    }

    // Delete the bad emoji
    emojiToBeDeleted.delete()

    // Undo the deletion mode as all emoji's are deleted
    if emojisArray.count == 0 {
        isDeletionMode = false
    }
}

I also have footers for every section, except for the last section, for that I have this in UICollectionViewDataSource

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        switch kind {
        case UICollectionElementKindSectionFooter:
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: Identifier.footer, for: indexPath)
            return headerView
        default:
            assert(false, "Unexpected element kind")
        }
}

and in UICollectionViewDelegate

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        switch collectionView {
        case stickerCollectionView:
            if section == emojisArray.count - 1 {
                return CGSize.zero
            }
            return CGSize(width: collectionView.bounds.size.width, height: 15)
        default:
            return CGSize.zero
        }
    }

Error -

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForSupplementaryElementOfKind: UICollectionElementKindSectionFooter at path {length = 2, path = 0 - 0}'

I am getting this error while deleting cells. And crash doesn't happen always, it is quite random.

sectionCollectionView is completely different UICollectionView.