gpt4 book ai didi

ios - 在 Collection View 中删除项目的正确方法

转载 作者:行者123 更新时间:2023-12-01 18:50:00 26 4
gpt4 key购买 nike

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

            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)
}
}

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

在 Collection View 中删除项目的正确方法是什么?

EDIT:/// Collection View 方法
  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
}

最佳答案

deleteItemsAtIndexPaths 中循环遍历您的数组之前,排序你的indexPaths按降序排列。那么,如果你删除第 19 项,则保证下一个要删除的项小于 19。

关于ios - 在 Collection View 中删除项目的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31807778/

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