gpt4 book ai didi

ios - 删除项目后 CollectionView 崩溃

转载 作者:行者123 更新时间:2023-11-30 11:36:01 26 4
gpt4 key购买 nike

我有一个 UICollectionView,它在 UITableViewCell 内水平滚动(附截图)。在collectionView中,第一个添加更多项目的单元格,旁边是俱乐部列表。

//MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return 1 + arrClubs.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.item == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellAdd, for: indexPath) as! FXFiltersAddCollectionViewCell

cell.layoutIfNeeded()

return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellTeam, for: indexPath) as! FXFiltersTeamCollectionViewCell

let isValidIndex = arrClubs.indices.contains(indexPath.item-1)
if isValidIndex == true {
let clubMO = Utils.clubFromId(clubId: arrClubs[indexPath.item-1])

cell.lbName.text = clubMO?.short_name
cell.imgLogo.setImage(url: clubMO?.icon, placeholder: nil)
}

cell.delegate = self

cell.layoutIfNeeded()

return cell
}
}

现在,我通过按“x”按钮删除每个单元格。

func didSelectRemoveClub(cell: FXFiltersTeamCollectionViewCell) {
if let indexPath = self.collectionView.indexPath(for: cell) {
self.collectionView.performBatchUpdates({
let isValidIndex = arrClubs.indices.contains(indexPath.item-1)
if isValidIndex == true {
arrClubs.remove(at: (indexPath.item - 1))

self.collectionView.deleteItems(at: [indexPath])
}
}, completion: { (finished) in

})
}
}

假设,我有 6 个俱乐部单元,我删除第 1、2、3 个俱乐部单元,它工作正常。然后我删除第四个单元格,它崩溃了:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndexedSubscript:]: index 3 beyond bounds [0 .. 2]'

但是如果在删除之前,我将 collectionView 滚动到最后一个单元格并返回第一个单元格,则效果很好!

enter image description here

最佳答案

在从数组中删除对象之前尝试以下更新删除集合单元:

func didSelectRemoveClub(cell: FXFiltersTeamCollectionViewCell) {
if let indexPath = self.collectionView.indexPath(for: cell) {
self.collectionView.performBatchUpdates({
let isValidIndex = arrClubs.indices.contains(indexPath.item)
if isValidIndex == true {

self.collectionView.deleteItems(at: [indexPath])
arrClubs.remove(at: (indexPath.item))
}
}, completion: { (finished) in

})
}
}

关于ios - 删除项目后 CollectionView 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49767030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com