如何从集合视图中删除多个选定的单元格? (迅速)
Posted
技术标签:
【中文标题】如何从集合视图中删除多个选定的单元格? (迅速)【英文标题】:How delete multiple selected cells from collection view? (swift) 【发布时间】:2018-08-22 11:21:34 【问题描述】:我在集合视图的所有单元格中有 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 搬出去)。'
【问题讨论】:
在numberOfRowsInSection
方法中,返回_selectedCells.count
,然后在每个didDelect
和didDeselect
方法中,重新调用。表格视图
【参考方案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”)
【讨论】:
很抱歉,我需要这个来收藏视图。我正在尝试更改 self.coll-ectionView.deleteItems(at: self.selectedCells) 并且当我按下 Delete 按钮时应用程序崩溃。 更新了我的答案【参考方案2】:您不能只从集合的数据源中删除项目,还必须告诉集合视图这些项目已被删除。为此,请使用deleteItems(at indexPaths: [IndexPath])
。如该方法的文档中所述,如果您想要一次进行多项更改,您也可以从performBatchUpdates(...)
调用它,例如如果您想同时添加项目和删除项目。
【讨论】:
以上是关于如何从集合视图中删除多个选定的单元格? (迅速)的主要内容,如果未能解决你的问题,请参考以下文章