删除项

时间:2018-04-11 05:18:38

标签: ios swift uicollectionview

我有一个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个俱乐部单元,它工作正常。然后我删除第4个单元格,它崩溃了:

  

由于未捕获的异常'NSRangeException'而终止应用程序,原因:'*** - [__ NSArrayM objectAtIndexedSubscript:]:索引3超出边界[0 .. 2]'

但是如果在删除之前,我将collectionView滚动到最后一个单元格并回归第一个单元格,它工作正常!

enter image description here

1 个答案:

答案 0 :(得分:0)

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

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

        })
    }
}