从UICollectionView删除单元格而无需重新加载

问题描述 投票:0回答:1

我的应用程序正在侦听套接字事件,该事件告诉它何时屏幕上的collectionView当前正在显示的数据有更新。发生这种情况时,我想从数据源和collectionView中删除与更新的行相对应的单元格。我可以这样做,如下所示:

  1. 过滤数据以仅包含其ID与已更新项目的ID不同的项目
  2. 将此新数据设置为collectionView使用的数据
  3. 重新加载collectionView

    socket.on(DATA_UPDATE) { (data, ack) in
           if let dat = data[0] as? [String: Any] {
              if let tabId = dat["tabId"] as? Int, let resId = dat["resId"] as? Int {
                 let remainingData = self.data?.filter{ $0.tabId != tabId }
                 if resId == self.restaurant?.id && remainingData?.count != self.data?.count {
                     self.data = remainingData
                     self.filterTableDataAndRelaod()
                 }
              }
           }
        }
    

问题是它会更新整个collectionView,并且还会向上滚动到顶部。我想使用以下代码来代替:

self.data.remove(at: indexPath.row)
collectionView.deleteItems(at: [indexPath])

但是,我不确定如何在上述代码片段中获取indexPath

ios swift uicollectionview uicollectionviewcell indexpath
1个回答
1
投票

您可以尝试

 var toDele = [IndexPath]()
    if let tabId = dat["tabId"] as? Int, let resId = dat["resId"] as? Int {
       for (index,item) in self.data?.enumerated() {
           if item.tabId == tabId {
              toDele.append(IndexPath(item:index,section:0)) 
           }
        } 

        for item in toDele {
            self.data?.remove(at:item.item)
        }
       collectionView.deleteItems(at:toDele )
  }

或如果您没有重复项

   if let tabId = dat["tabId"] as? Int, let resId = dat["resId"] as? Int {
       if let ind = self.data?.firstIndex(where:{ $0.tabId == tabId }) {
            self.data?.remove(at:ind) 
            collectionView.deleteItem(at:IndexPath(item:ind,section:0))
       }
   }
© www.soinside.com 2019 - 2024. All rights reserved.