简体   繁体   English

Swift CollectionView删除异常

[英]Swift CollectionView Deletion Exception

I'm trying to delete a collectionView cell using this code : 我正在尝试使用以下代码删除collectionView单元格:

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 : 它是非常直接的删除,并在尝试删除第1节中的任何单元格后,它会导致此异常:

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).' 由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'无效更新:第1节中的无效项目数。更新后的现有部分中包含的项目数(2)必须等于该项目中包含的项目数更新前的部分(2),加上或减去从该部分插入或删除的项目数(插入0,删除1),加上或减去移入或移出该部分的项目数量(0移入,0移动)出)。”

my collectionView distribution for cells is each section contains 2 cells like image below 我的单元格的collectionView分布是每个部分包含2个单元格,如下图所示 我的收藏视图

and for last section if its containing 1 cell , it will contain 1 cell 对于最后一节,如果它包含1个单元格,它将包含1个单元格

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). 正确的方法是在更新块内部删除数据源,否则您可以在更新块之外进行更改,但确保UI在更新开始之前匹配(重新加载)(您没有)。

Try moving myDataSourceArray.remove(at:index) inside the update block. 尝试在更新块内移动myDataSourceArray.remove(at:index)

https://developer.apple.com/documentation/uikit/uicollectionview/1618045-performbatchupdates 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(:) . 如果删除操作导致删除某个部分的最后一个单元格,则必须使用deleteSections(:)删除该部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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