我有一個包含兩個部分的collectionView,每個部分用單獨的數組填充單元格。將項目從一個UICollectionView部分移動到另一個時發生崩潰,然後刪除該項目
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 && GlobalList.priorityArray.count != 0 {
return GlobalList.priorityArray.count
} else if section == 1 && GlobalList.listItemArray.count != 0 {
return GlobalList.listItemArray.count
} else {
return 0
}
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return sections
}
我可以在各部分之間移動項目,不會有任何問題。我也可以刪除項目。我在部分之間移動項目時重新加載數據,然後嘗試刪除該部分中的所有項目,出現以下錯誤。
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (3) must be equal to the number of items contained in that section before the update (3), 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).'
下面是我創建處理刪除和移動項目
移動項目的方法:
override func collectionView(_ collectionView: UICollectionView,
moveItemAt sourceIndexPath: IndexPath,
to destinationIndexPath: IndexPath) {
if (sourceIndexPath as NSIndexPath).section == 0 {
listItem = GlobalList.priorityArray.remove(at: sourceIndexPath.item)
} else if (sourceIndexPath as NSIndexPath).section == 1 {
listItem = GlobalList.listItemArray.remove(at: sourceIndexPath.item)
}
if (destinationIndexPath as NSIndexPath).section == 0 {
GlobalList.priorityArray.insert(listItem, at: destinationIndexPath.item)
} else if (destinationIndexPath as NSIndexPath).section == 1 {
GlobalList.listItemArray.insert(listItem, at: destinationIndexPath.item)
}
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(reloadData), userInfo: nil, repeats: false)
}
刪除項目:
func deleteItem(sender: UIButton) {
let point : CGPoint = sender.convert(.zero, to: collectionView)
let i = collectionView!.indexPathForItem(at: point)
print("deleting.. \(String(describing: i))")
let index = i
GlobalList.listItemArray.remove(at: (index?.row)!)
deleteItemCell(indexPath: i!)
}
func deleteItemCell(indexPath: IndexPath) {
collectionView?.performBatchUpdates({
self.collectionView?.deleteItems(at: [indexPath])
}, completion: nil)
}
讓我知道如果有什麼否則需要解決這個問題。
在此先感謝!
嘗試調用'self.collectionView .deleteItems(在:indexPath])',而不是直接的內部執行批量更新。 –