【问题标题】:correct way of deleting items in collection view在集合视图中删除项目的正确方法
【发布时间】:2015-08-04 20:31:37
【问题描述】:

我有一个存储在图片数组中的 20 个项目的集合视图。我正在使用此代码删除选定的项目:

            self.collectionView.performBatchUpdates({
            let selectedItems = self.collectionView.indexPathsForSelectedItems()!
            self.picturesObject.deleteItemsAtIndexPaths(selectedItems)
            self.collectionView.deleteItemsAtIndexPaths(selectedItems)

            }, completion: {_ in})

这是picturesObject的deleteItemsAtIndexPaths的实现:

func deleteItemsAtIndexPaths(indexPaths:[NSIndexPath]){
        for indexPath in indexPaths{
            pictures.removeAtIndex(indexPath.item)
        }
    }

我面临的问题如下。每次删除集合视图中的选定项目时,图片数组都会变小。如果我删除第一项,图片数组只有 19 项大。如果我尝试删除集合视图中的第 20 项,则数组索引会超出范围,因为图片数组现在只有 19 个对象大,但我想删除存储在 indexpath.item 中的第 20 个对象。

在集合视图中删除项目的正确方法是什么?

EDIT:/// 集合视图方法

  func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        collectionView.allowsMultipleSelection = true

        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picturesObject.pictures.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! ShopCell
        cell.imageView.image = picturesObject.pictures[indexPath.item]

        return cell
    }

【问题讨论】:

  • 嗨,我认为您删除了数组中的图像,但您的 dataSource 委托方法在内存中保留了 20 个项目。您可以粘贴您的 collectionView 委托方法吗?
  • 你去。我编辑了我的问题。我认为它们是数据源方法,没有其他方法。

标签: ios arrays uicollectionview uicollectionviewcell


【解决方案1】:

在遍历deleteItemsAtIndexPaths 中的数组之前,请按降序对indexPaths 进行排序。那么,如果你删除第19项,保证下一个要删除的项小于19。

【讨论】:

  • 我不确定是否理解。你能提供例子吗?我不应该以某种方式更新collectionView中单元格的indexPaths吗?我也在同时删除多个选定的项目。
  • 您有 20 个项目,编号为 0 到 19。如果你先删除 0,那么删除 19 就会崩溃,因为它已经不存在了。如果先删除 19,则删除 0 时一切正常。因此,如果对 indexPaths 进行排序,以便循环使用 indexPath.item 的较高值,然后再使用较低的值,则可以避免此问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 2020-05-15
  • 2021-10-07
相关资源
最近更新 更多