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

时间:2018-08-22 11:21:34

标签: arrays swift uicollectionview

在集合视图中,我所有的单元格中都有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移出)。'

2 个答案:

答案 0 :(得分:1)

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



}

答案 1 :(得分:0)

您不仅可以从集合的数据源中删除项目,还必须告诉集合视图这些项目已被删除。为此,请使用deleteItems(at indexPaths: [IndexPath])。如该方法的文档中所述,如果您要一次全部进行多项更改,例如也可以从performBatchUpdates(...)调用它。如果您要同时添加和删除项目。