简体   繁体   中英

Swift CollectionView Deletion Exception

I'm trying to delete a collectionView cell using this code :

myDataSourceArray.remove(at:index)
collectionView.performBatchUpdates({
collectionView.deleteItems(at: [indexPath])
}
, completion: nil)

its very straight forward deletion ,and after trying to delete any cell from section 1 for example , it causes this exception :

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of items in section 1. The number of items contained in an existing section after the update (2) must be equal to the number of items contained in that section before the update (2), plus or minus the number of items inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).'

my collectionView distribution for cells is each section contains 2 cells like image below 我的收藏视图

and for last section if its containing 1 cell , it will contain 1 cell

func collectionView(_ collectionView: UICollectionView, 
numberOfItemsInSection section: Int) -> Int {
    if myDataSourceArray.count%2==1 && myDataSourceArray.count/2 == section {
        return 1
    }else{
        return 2
    }
}

What exactly causes this exception ? Thanks in advance :)

Your problem is likely caused by the fact that you're not handling the deletion from the data source correctly.

The proper way to do it is to do the data source deletion inside of the update block, otherwise you can do the changes outside the update block but make sure the UI matches (reload it) before the update begins (which you did not).

Try moving myDataSourceArray.remove(at:index) inside the update block.

https://developer.apple.com/documentation/uikit/uicollectionview/1618045-performbatchupdates

The other thing which is probably not causing the issue but that you should be handling regardless (that I don't see you doing here), is sections have to be manually deleted. If your deletion operation results in the last cell of a section being deleted, you have to delete the section as well using deleteSections(:) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM