我要删除UICollectionView中具有特定ID的单元格。因此该单元格可以位于视图的中间。
为此,我从单元格数组中删除了该项目,还删除了indexPath。必须首先检索indexPath。这是不可能的!
不可见/不可见的单元格(在当前视图下方,必须向上滚动)无法删除,因为它们原来是NIL。
如何访问具有ID的特定单元格并将其删除?
let cellIdToFeedItem_ToDelete = [ String : FeedItem ]() // here are the item to be deleted
var indexPathsToRemove = [ IndexPath ]()
var indexPathsAllActive = [ IndexPath ]() // Will be filled below
// --- retrieving all indexPaths
if let nrSections = self.collectionView?.numberOfSections
{
for s in 0..<nrSections
{
if let v = self.collectionView?.numberOfItems( inSection: s )
{
for i in 0..<v
{
let indexPathTMP = IndexPath( item: i, section: s )
indexPathsAllActive.append( indexPathTMP )
}
}
}
}
// --- delete the items with the same
for indexPath in indexPathsAllActive
{
// #### FOR HIDDEN CELLS THIS IS 'NIL'
let cell = self.collectionView?.cellForItem( at: indexPath ) as? FeedCollectionViewCell
if let cellID = cell?.id
{
if let _ = cellIdToFeedItem_ToDelete[ cellID ]
{
if let index = feedItemsActive_.firstIndex( where: {
(i) -> Bool in
i.id == cellID
} )
{
feedItemsActive_.remove( at: index )
indexPathsToRemove.append( indexPath )
}
}
}
}
self.collectionView?.deleteItems( at: indexPathsToRemove )
答案 0 :(得分:3)
从数据源(我认为是indexPathsAllActive?)中删除项目,然后重新加载collectionView以显示更改。
没有动画:
collectionView.reloadData()
带有动画:
collectionView.performBatchUpdates{ }
以下是在代码中使用performBatchUpdates的方法:(如果有一部分的话)
collectionView?.performBatchUpdates({
var targetIndexPaths: [IndexPath] = []
for ( cellID, _ ) in cellIdToFeedItem_ToDelete
{
if let index = feedItemsActive_.firstIndex( where: { $0.id == cellID } )
{
feedItemsActive_.remove( at: index )
targetIndexPaths.append(IndexPath(item: index, section: 0))
}
}
collectionView?.deleteItems(at: targetIndexPaths])
}, completion: nil)
答案 1 :(得分:0)
这完成了工作。但没有动画:
for ( cellID, _ ) in cellIdToFeedItem_ToDelete
{
if let index = feedItemsActive_.firstIndex( where: {
(i) -> Bool in
i.id == cellID
} )
{
feedItemsActive_.remove( at: index )
}
}
self.collectionView?.reloadData()