首页 > 解决方案 > 如何从集合视图中删除多个选定的单元格?(迅速)

问题描述

我在集合视图中的所有单元格中有 5 个数组。

如何从集合视图中删除多个选定的单元格?

var _selectedCells : NSMutableArray = []

删除按钮

@IBAction func DeleteButton(_ sender: UIBarButtonItem) {
       // How delete multiple selected cells from collection view
}

添加单元格索引

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
     if self.EditToolBar.isHidden == true {
          self.performSegue(withIdentifier: "DetailVC", sender: indexPath.item)
     } else {
          print("EditMode")
          _selectedCells.add(indexPath)
          print("selectedCells - \(_selectedCells)")
     }
}

删除单元格索引

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
     if self.EditToolBar.isHidden == true {
     } else {
          print("EditMode")
          _selectedCells.remove(indexPath)
          print("unselectedCells - \(_selectedCells)")
     }
}

碰撞

*** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新:第 0 节中的项目数无效。更新后现有节中包含的项目数 (5) 必须等于项目数更新前包含在该节中的项目数 (5),加上或减去从该节插入或删除的项目数(0 插入,2 个删除),加上或减去移入或移出该节的项目数(0 移入, 0 移出)。

标签: arraysswiftuicollectionview

解决方案


var _selectedCells = [IndexPath]()

添加单元格索引

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
     if self.EditToolBar.isHidden == true {
          self.performSegue(withIdentifier: "DetailVC", sender: indexPath.item)
     } else {
          print("EditMode")
         if !(_selectedCells.contains(indexPath)) {
              _selectedCells.add(indexPath)
              print("selectedCells - \(_selectedCells)")
         }

     }
}

删除单元格索引

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
     if self.EditToolBar.isHidden == true {
     } else {
          print("EditMode")

        if let index = _selectedCells.index(where: { $0 == indexPath }) {
       _selectedCells.remove(at: index)
        print("unselectedCells - \(_selectedCells)")

         }   
     }
}

删除按钮操作

@IBAction func DeleteButton(_ sender: UIBarButtonItem) {
       // Two Things To make sure of 
       // 1. Never call reloadData() right after insert/move/deleteRows..., the insert/move/delete operation reorders the table and does the animation
       // 2. Call insert/move/deleteRows... always after changing the data source array.


       // remove the data from data Source Array you passed ,of selected cells you're trying to delete .

     self.collectionView.performBatchUpdates({
         self.collectionView.deleteItems(at indexPaths: _selectedCells)
     }){
              // optional closure
            print(“finished deleting cell”)
      }



}

推荐阅读