【发布时间】:2018-09-20 01:56:04
【问题描述】:
我想删除 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 )
【问题讨论】:
-
你为什么要得到细胞?单元格是视图,而不是您的数据。遍历您的数据模型,而不是单元格。
-
我正在获取单元格以获取 ID。我应该迭代什么来发现我正在删除正确的?
-
正如我所说,迭代你的数据模型。这就是 id 最初的来源。
标签: ios swift uicollectionview